【问题标题】:Selenium Python Stale element reference: element is not attached to the page documentSelenium Python Stale 元素参考:元素未附加到页面文档
【发布时间】:2021-07-05 16:56:46
【问题描述】:

所以我正在尝试制作一个可以在 flickr 上运行的程序,我已经完成了所有工作,直到弹出 cookie 打败了我。

   <iframe src="https://consent-pref.trustarc.com/?type=flickr_iab&amp;layout=iab&amp;site=flickr.com&amp;action=notice&amp;country=gb&amp;locale=en&amp;behavior=expressed&amp;gtm=1&amp;iab=true&amp;irm=undefined&amp;from=https://consent.trustarc.com/" id="pop-frame016812901338164787" title="TrustArc Cookie Consent Manager" tabindex="1" scrolling="no" style="border: 0px none; border-radius: 2px; overflow: hidden; background: rgb(255, 255, 255) none repeat scroll 0% 0%; display: block; position: absolute; top: 0px; left: 0px; width: 100%; height: 834px;"></iframe>

我正在尝试切换到此 iframe,以便可以使用“全部接受”按钮。但是 iframe 的 ID 是动态的,因此为了解决这个问题,我尝试以标题为目标。

xpath = """//iframe[contains(@title, 'TrustArc Cookie Consent Manager')]"""
iframe = browser.find_element_by_xpath(xpath);

driver.switch_to.frame(iframe);

但是我现在收到此错误消息。

 File "flickrbot.py", line 28, in <module>
    driver.switch_to.frame(iframe);
  File "C:\Users\IMFro\.virtualenvs\Desktop-LBlgM1Hj\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 89, in frame
    self._driver.execute(Command.SWITCH_TO_FRAME, {'id': frame_reference})
  File "C:\Users\IMFro\.virtualenvs\Desktop-LBlgM1Hj\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\IMFro\.virtualenvs\Desktop-LBlgM1Hj\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=91.0.4472.124)

我尝试添加 10 秒的等待时间以使其有时间加载,我理解错误的原因是该元素不再附加到 DOM,但我不知道要使用什么其他参考。

任何建议都会有很大帮助!另外我对 python 非常陌生,所以如果你能告诉我你正在向一个 5 岁的孩子解释,那将不胜感激啊哈哈哈

【问题讨论】:

    标签: python-3.x selenium selenium-webdriver selenium-chromedriver


    【解决方案1】:

    你可以试试explicit waits

    wait = WebDriverWait(driver, 10)
    wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[contains(@title, 'TrustArc Cookie Consent Manager')]")))
    

    进口:

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

    【讨论】:

    • 嘿!感谢您的答复!令人讨厌的是,它仍然无法等待超时:(
    • 我可以有实际的网址吗?
    • 嘿,当然!!这是 www.flickr.com
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2019-04-27
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    相关资源
    最近更新 更多