【问题标题】:Python Selenium StaleElement ExceptionPython Selenium StaleElement 异常
【发布时间】: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


    【解决方案1】:
    links =[ x.get_attribute('href') for x in driver.find_element_by_id('questions').find_elements_by_tag_name('a')]
    driver.get(links[0])
    driver.back()
    

    只需获取href值并像这样来回走动。您从页面获取的元素会在页面移动时丢失。

    【讨论】:

    • 如果有帮助,请点赞并接受我的回答。
    猜你喜欢
    • 1970-01-01
    • 2019-05-12
    • 2021-02-25
    • 2021-10-02
    • 1970-01-01
    • 2021-11-24
    • 2020-04-25
    • 2016-07-01
    相关资源
    最近更新 更多