问答

selenium元素找不到问题

作者:admin 2021-05-11 我要评论

操作是登录了一个网站(论坛)后,试图点击新页面中的一个超链接发现有一定概率会报错。报错提示如下: selenium.common.exceptions.StaleElementReferenceExcep...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

操作是登录了一个网站(论坛)后,试图点击新页面中的一个超链接发现有一定概率会报错。报错提示如下:
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=87.0.4280.88)

源代码如下

from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get('http://127.0.0.1/upload/forum.php')
driver.find_element_by_css_selector("#ls_username").send_keys('admin')
driver.find_element_by_css_selector('#ls_password').send_keys('123456')
driver.find_element_by_css_selector('.pn.vm').click()
driver.find_element_by_link_text('默认版块').click()
  • 代码是加了隐式等待的不起作用
  • 这个元素偶尔会找不到,但多数是可以找到的。

网上找了下,发现官方说是2个原因:

  • The element has been deleted entirely.
  • The element is no longer attached to the DOM.
###

就是前端元素不存在,具体为什么不存在要具体分析了。可能是没加载出来,可能是前端对元素处理了。

显式设置对元素等待试试看

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

localBy =  (By.CSS_SELECTOR, "#ls_username",)
until = EC.presence_of_element_located(localBy)
element = WebDriverWait(driver, 10).until(until)
element.send_keys('admin')

# TOOD
# ...

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • selenium元素找不到问题

    selenium元素找不到问题

  • H5 WEB ,点击 Notification,当窗口不

    H5 WEB ,点击 Notification,当窗口不

  • 怎样把echarts图表做成响应式的?怎样

    怎样把echarts图表做成响应式的?怎样

  • java 看了一个框架源码不知原因

    java 看了一个框架源码不知原因

腾讯云代理商
海外云服务器