我试图用Selenium Python和Chrome浏览器下载一个网页上的所有pdf文件,但每次会话结束时都会显示以下消息:
StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=52.0.2743.116)
(Driver info: chromedriver=2.22.397933代码如下:
def download_pdf(self):
current = self.driver.current_url
lista_link_temp = self.driver.find_elements_by_xpath("//*[@href]")
for link in lista_link_temp:
if "pdf+html" in str(link.get_attribute("href")):
tutor = link.get_attribute("href")
self.driver.get(str(tutor))
self.driver.get(current)请帮帮我..我刚刚尝试了lambda,隐式和显式的等待
谢谢
发布于 2016-09-17 11:28:26
只要在循环中调用self.driver.get(),元素列表中的所有其他元素就会变得陈旧。尝试首先从元素中收集href属性,然后访问它们:
def download_pdf(self):
current = self.driver.current_url
lista_link_temp = self.driver.find_elements_by_xpath("//*[@href]")
pdf_hrefs = []
# You could do this part with a single line list comprehension too, but would be really long...
for link in lista_link_temp:
href = str(link.get_attribute("href"))
if "pdf+html" in href:
pdf_hrefs.append(href)
for h in pdf_hrefs:
self.driver.get(h)
self.driver.get(current)发布于 2016-09-17 06:02:47
当你搜索一个元素,并且在对它执行任何操作之前,页面已经改变/重新加载,你就会得到陈旧的元素。
在页面中执行任何操作之前,请确保页面已完全加载。
因此,您需要首先添加一个条件,以等待页面加载,并可能检查所有请求是否已完成。
https://stackoverflow.com/questions/39540160
复制相似问题