简体   繁体   中英

How locate the Sign in button within https://twitter.com using Python Selenium

I am writing a script in python that logs in twitter however whenever i try to locate the log-in button in selenium it gives an error

Python code:

driver= webdriver.Firefox()
driver.get("https://twitter.com")
login_button= driver.find_element(By.XPATH, "//a[@href='/i/flow/signup']")         print(login_button)

Source of the target element:

登录按钮元素的来源:

The error:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //a[@href='/i/flow/signup']

I have even tried copying the absolute path of the element:

driver= webdriver.Firefox()
driver.get("https://twitter.com")
login_button= driver.find_element(By.XPATH, "/html/body/div/div/div/div[2]/main/div/div/div[1]/div[1]/div/div[3]/a")
print(login_button)

This gives the error:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div/div/div/div\[2\]/main/div/div/div\[1\]/div\[1\]/div/div\[3\]/a

As error says: Unable to locate element. You can use wait to "wait" until your element is located. For more you can see: https://selenium-python.readthedocs.io/waits.html So you can do that as following code:

#import necessary parts
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

#wait
wait = WebDriverWait(driver, 10)

#from your code
driver= webdriver.Firefox()
driver.get("https://twitter.com")
login_button = wait.until(EC.presence_of_element_located((By.XPATH, "//a[@href='/i/flow/signup']"))).click() #it will click the button.

To click on Sign in button within Twitter Login Page you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies :

  • Using CSS_SELECTOR :

     driver.get('https://twitter.com/') WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href='/login'] span > span"))).click()
  • Using XPATH :

     driver.get('https://twitter.com/') WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Sign in']"))).click()
  • Note : You have to add the following imports:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
  • Browser Snapshot:

推特登录

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM