脚本无法找到Twitter的密码字段

时间:2019-10-17 13:02:24

标签: python selenium selenium-webdriver twitter

在这个使用Selenium的超级基本python脚本中,我只是试图自动化我的Twitter登录,以便开始抓取。 chrome会话打开时,将填写用户名,但密码字段保留为空。

import bs4
from selenium import webdriver

driver = webdriver.Chrome();
url = "https://twitter.com/login"
driver.get(url)
assert "Twitter" in driver.title

username = driver.find_element_by_class_name('js-username-field')
username.send_keys('example_username')


password = driver.find_element_by_class_name('js-password-field')
password.clear()
password.send_keys('exmaple_password')

login_button = driver.find_element_by_css_selector("button.submit.EdgeButton.EdgeButton--primary.EdgeButtom--medium")
login_button.submit()

1 个答案:

答案 0 :(得分:0)

可能需要在密码字段上添加wait。如果您遇到脚本间歇性问题,这将有所帮助。我更喜欢在元素上wait,而不是sleep

import bs4
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


driver = webdriver.Chrome();
url = "https://twitter.com/login"
driver.get(url)
assert "Twitter" in driver.title

username = driver.find_element_by_class_name('js-username-field')
username.send_keys('example_username')

# wait on password field
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'js-password-field')))

password = driver.find_element_by_class_name('js-password-field')
password.clear()
password.send_keys('exmaple_password')

login_button = driver.find_element_by_css_selector("button.submit.EdgeButton.EdgeButton--primary.EdgeButtom--medium")
login_button.submit()

Python很快就完成了各个步骤,有时需要一段时间才能赶上网页。添加wait可以使速度变慢,并且可以修复您可能会看到的一些间歇性错误。