[英]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 中编写一个脚本,用于登录 twitter,但是每当我尝试在 selenium 中找到登录按钮时,它都会出错
Python code: Python 代码:
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.
您可以使用 wait 来“等待”直到找到您的元素。 For more you can see: https://selenium-python.readthedocs.io/waits.html So you can do that as following code:
更多可以看: https://selenium-python.readthedocs.io/waits.html所以你可以像下面的代码那样做:
#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 :要单击Twitter 登录页面中的登录按钮,您需要为element_to_be_clickable()引入WebDriverWait ,您可以使用以下任一定位器策略:
Using CSS_SELECTOR :使用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 :使用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:浏览器快照:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.