【问题标题】:Cannot type Password via SendKeys() in Selenium Python无法在 Selenium Python 中通过 SendKeys() 输入密码
【发布时间】:2020-10-11 16:14:49
【问题描述】:

我正在尝试使用 Selenium WebScraping 编写一个程序来与我的电子邮件交互。我在下面粘贴的代码仅用于登录过程。我更改了电子邮件和密码。

from selenium import webdriver

#Edge
driver = webdriver.Chrome()

#Open the website
driver.get('https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=13&ct=1602431674&rver=7.0.6737.0&wp=MBI_SSL&wreply=https%3a%2f%2foutlook.live.com%2fowa%2f%3fnlp%3d1%26RpsCsrfState%3d2c3ee82f-9893-34e5-fd04-e3b4c3e2ccc4&id=292841&aadredir=1&CBCXT=out&lw=1&fl=dob%2cflname%2cwld&cobrandid=90015')

log_in_button = driver.find_element_by_name("loginfmt")

log_in_button.send_keys('myemail@outlook.com')

next_button = driver.find_element_by_id("idSIButton9")

next_button.click()

password_button = driver.find_element_by_name("passwd")

password_button.send_keys('my_password')

但是,当我运行此程序时(使用正确的电子邮件和密码),程序似乎无法在最后一步输入密码。没有错误日志,我的程序输入我的电子邮件就好了,但它无法输入密码。我尝试使用几种不同的方法来定位 HTML 元素,包括

find_element_by_type()

find_element_by_id()

find_element_by_class_name()

还有

find_element_by_css_selector()

这些方法中的大多数以 StaleElementReferenceException 告终,有些以无法定位元素告终,其余的根本不起作用。

有谁知道通过 Selenium 输入密码的方法,我假设我使用了错误的元素,或者 Microsoft 出于某种原因故意阻止了这种行为。

非常感谢任何帮助。谢谢。

【问题讨论】:

  • 在下一个按钮单击后添加几秒的暂停,适当的 5 秒。或使用expected conditions,如果你想要它真的很快
  • @gulbazkhan 成功了!您应该将其写为答案,以便我可以接受它,以便其他人在遇到相同问题时可以轻松找到它。非常感谢您的帮助!

标签: python selenium web-scraping


【解决方案1】:

最佳做法是尽可能避免使用time.sleep()time.sleep()不必要地减慢你的脚本。

最佳做法是始终使用显式等待来避免同步问题。

使用WebDriverWait() 并等待element_to_be_clickable()

password_button =WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.NAME,"passwd")))

您需要导入以下库。

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

进一步的学习可以参考下面Explicit Waits

【讨论】:

  • 感谢您的提示
猜你喜欢
  • 2012-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多