selenium元素找不到问题

吴贤峰
  • 1
新手上路,请多包涵

操作是登录了一个网站(论坛)后,试图点击新页面中的一个超链接发现有一定概率会报错。报错提示如下:
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.
回复
阅读 1.5k
1 个回答

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

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

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
# ...
宣传栏