Selenium Python Stale元素引用:元素未附加到页面文档



所以我正在尝试制作一个在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:UsersIMFro.virtualenvsDesktop-LBlgM1Hjlibsite-packagesseleniumwebdriverremoteswitch_to.py", line 89, in frame
self._driver.execute(Command.SWITCH_TO_FRAME, {'id': frame_reference})
File "C:UsersIMFro.virtualenvsDesktop-LBlgM1Hjlibsite-packagesseleniumwebdriverremotewebdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:UsersIMFro.virtualenvsDesktop-LBlgM1Hjlibsite-packagesseleniumwebdriverremoteerrorhandler.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岁的孩子解释一样,那将非常感谢哈哈哈哈

您可以尝试使用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

最新更新