所以我使用 Selenium 抓取链接。我可以用循环打印我的链接,但我无法导航到它们,因为我收到以下错误:
selenium.common.exceptions.StaleElementReferenceException:消息:元素引用已过时;元素不再附加到 DOM,不在当前框架上下文中,或者文档已刷新
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.famousgraphicdesigners.org/")
links = driver.find_elements_by_xpath('//*[@id="pages-2"]/div/ul/li/a')
links_total = len(links)
print("Found", links_total, "total links.\n")
for i in links:
# print(i.get_attribute('href')) # This works
driver.get(i.get_attribute('href')) # This doesnt work
driver.quit()
最佳答案
当您导航到新页面时,先前定位的元素将变得陈旧,在这种情况下,links
中的元素将失效。 ,因此您无法访问 href
属性。保留所有 href
s 在字符串列表中并对其进行迭代
links = driver.find_elements_by_xpath('//*[@id="pages-2"]/div/ul/li/a')
links_hrefs = [link.get_attribute('href') for link in links]
for i in links_hrefs:
driver.get(i)
关于python - 陈旧;元素不再附加到 DOM,不在当前框架上下文中,或者文档已刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59016107/