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



我的程序正在抛出一条错误消息"失效元素引用:元素未附加到页面文档"。当我查看以前的文章(如PythonSenium-stateelementfix(时,我发现在调用click函数后没有更新url。我更新了网址。然而,它并没有解决这个问题。有人能指出我哪里搞错了吗?这是我的代码:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-infobars")
driver = webdriver.Chrome(chrome_options=chrome_options,executable_path="path of driver here")
driver.get("https://stackoverflow.com/users/37181/alex-gaynor?tab=topactivity")
if driver.find_elements_by_xpath("//a[@class='grid--cell fc-white js-notice-close']"):
driver.find_element_by_xpath("//a[@class='grid--cell fc-white js-notice-close']").click()

inner_tabs = driver.find_elements_by_xpath("//div[@class='tabs']//a")
for inner_tab in inner_tabs:
if inner_tab.text == "answers":
inner_tab.click()
time.sleep(3)
driver.get(driver.current_url)
continue
if inner_tab.text == "questions":
inner_tab.click()
time.sleep(3)
driver.get(driver.current_url)
continue
driver.quit()

当您通过单击链接或driver.get()打开新的URL时,它将创建新的文档元素,因此旧的元素(inner_tab(将无效。要解决此问题,首先收集所有URL,然后在循环中打开。

urls_to_visit = []
for inner_tab in inner_tabs:
if inner_tab.text in ["questions", "answers"]:
urls_to_visit.append(inner_tab.get_attribute("href"))
for url in urls_to_visit:
driver.get(url)
time.sleep(3)

这是Selenium中最令人沮丧的错误之一。我建议这样试试:

for tab in ['answers', 'questions']:
js = "window.tab = [...document.querySelectorAll('div.tabs > a')].filter(a => a.innerText === '" + tab + "')[0]"
driver.execute_script(js)
driver.execute_script("if(window.tab) window.tab.click()")
time.sleep(3)
print(driver.current_url)

通过在浏览器上下文中进行选择,可以避免过时的引用。

最新更新