繁体   English   中英

Selenium Python StaleElementReferenceException

[英]Selenium Python StaleElementReferenceException

我正在尝试使用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,隐式和显式等待

谢谢

当您搜索元素时,在对其执行任何操作之前,页面已更改/重新加载,您将获得陈旧元素。

在页面中执行任何操作之前,请确保页面已完全加载。

因此,您需要先添加一个条件来等待页面加载,或者检查所有请求是否完成。

只要在循环中调用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM