【发布时间】:2021-04-08 16:50:56
【问题描述】:
我正在寻找使用 Selenium 导航回上一页时出现的 StaleElementReferenceException 的解决方案。
这里是重现错误的示例代码:
from selenium.webdriver import Chrome
from selenium.common.exceptions import NoSuchElementException
browser = Chrome()
browser.get('https://stackoverflow.com/questions/')
# Closing the pop-up for cookies
try:
browser.find_element_by_class_name('js-accept-cookies').click()
except NoSuchElementException:
pass
# Getting list of links on a StackOverflow page
links = browser.find_element_by_id('questions').find_elements_by_tag_name('a')
links[0].click()
# Going back
browser.back()
try:
browser.find_element_by_class_name('js-accept-cookies').click()
except NoSuchElementException:
pass
# Using the old links
links[1].click()
我从类似 Stale Element Reference Exception: How to solve? 这样的类似 stackoverflow 问题中了解了根本原因
但是,由于性能原因,建议的解决方案(即每次导航返回时重新获取链接)不适合我。
还有其他选择吗?
例如强制新页面在新选项卡中打开,以便我可以在两个选项卡之间导航?
感谢任何其他解决方案
【问题讨论】:
标签: python selenium staleelementreferenceexception staleobjectstateexception selenium-webdriver-python