Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

selenium元素找不到问题

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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
# ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...