【问题标题】:Python - Selenium Stale exceptionPython - Selenium 陈旧异常
【发布时间】:2021-10-02 03:02:14
【问题描述】:

我正在尝试自动化 Microsoft 登录页面。但是,当我尝试单击登录按钮时,不会发生错误,但按钮没有被单击。

使用的语言 - Python

下面是我的代码

from selenium import webdriver
driver=webdriver.chrome()
url=https://login.microsoftonline.com/
driver.get(url)
button=driver.find.element_by_xpath('//*[@id="idSIButton9"])
username=driver.find.element_by_id("i0116")
username.clear()
username..sendkeys(zyz@gmail.com)
button.click()
password =driver.find.element_by_id("i0118")
password.clear()
password.sendkeys(zyzass)
try:
   button.click()
expect StaleElementReferenceException:
   print("loggedin")

预期结果 - 1.登录https://login.microsoftonline.com/ 2.输入用户名 3.点击下一步按钮 4.输入密码 5.点击登录

实际结果 - 1.登录https://login.microsoftonline.com/ 2.输入用户名 3.点击下一步按钮 4.输入密码 5.点击无效

代码运行时没有错误。

【问题讨论】:

  • 你能接受你评论的答案吗?

标签: python selenium-webdriver ui-automation


【解决方案1】:

这是陈旧元素问题的经典例子。
您通过

获得了next 按钮
button=driver.find.element_by_xpath('//*[@id="idSIButton9"])

一开始。
然后您插入电子邮件地址并按下next 按钮。
现在您在另一个网页上,对位于前一页上的元素的指针/引用不再有效。
因此,当您现在尝试访问上一页定义的元素时,

button.click()

它不起作用。
抛出过时元素异常。
要使其正常工作,您必须使用

再次定义/获取next 按钮元素
button=driver.find.element_by_xpath('//*[@id="idSIButton9"])

在您的代码运行中实际上没有出现错误,因为您正在捕获异常

try:
   button.click()
expect StaleElementReferenceException:

阻止,但是当您在系统内打印时,您仍然不在系统内

expect StaleElementReferenceException:
   print("loggedin")

阅读有关 Stale Element here 或任何其他可用教程的更多信息。

【讨论】:

    【解决方案2】:
    I have checked with these lines of code, and it works fine there are 
    lots of syntactical error in your code, So I've tried with the correct ways, You can check with this
    
    browser.maximize_window()
    
    userId = WebDriverWait(browser,10).until(EC.visibility_of_element_located((By.XPATH,"//input[@type='email' and @name='loginfmt']")))
    userId.send_keys("zyz@gmail.com")
    
    next=WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,"//input[@id='idSIButton9']")))
    next.click()
    
    password = WebDriverWait(browser,10) .until(EC.visibility_of_element_located((By.XPATH,"//input[@type='password' and @name='passwd']")))
    password.send_keys("zyzass")
    
    signIn=WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,"//*[@value='Sign in']")))
    signIn.click()
    

    我用过explicitWait

    导入

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 2015-08-30
      • 1970-01-01
      相关资源
      最近更新 更多