【问题标题】:Python Selenium: I am getting element is not attached to the page document errorPython Selenium:我正在获取元素未附加到页面文档错误
【发布时间】:2020-07-31 11:55:58
【问题描述】:

我正在尝试使用 selenium 包为 python 构建一个爬虫,但我收到了这个错误:

Message: stale element reference: element is not attached to the page document
  (Session info: headless chrome=83.0.4103.61)

我正在使用谷歌 colab。 我的代码是:

import selenium
driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
titles=[]
for link in links:
  driver.get(link)
  data = driver.find_elements_by_xpath('.//a[@class = "question-hyperlink"]')
  titles.append(data[0].text)

错误在data = driver.find_elements_by_xpath('.//a[@class = "question-hyperlink"]')一行

有人告诉我尝试异常处理,但我无法实现它。请帮助我如何实现它。

【问题讨论】:

  • 异常处理是 tryexcept 围绕您想要捕获的内容 - 在这里阅读 docs.python.org/3/tutorial/errors.html - 如果您尝试发布带有特定错误的代码,我们可以提供帮助: -)

标签: python selenium xpath selenium-chromedriver


【解决方案1】:

迭代链接列表时似乎存在同步问题。 诱导WebDriverWait(),等待visibility_of_all_elements_located(),然后迭代存储到列表中。

使用 try..except 块来处理。

代码

titles=[]
for link in links:
  driver.get(link)
  try:
      data=WebDriverWait(driver,10).until(EC.visibility_of_all_elements_located((By.XPATH,'//a[@class = "question-hyperlink"]')))
      for d in data:
        titles.append(d.text)
  except:
      print("element not found")
      continue

您需要导入以下库。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

【讨论】:

  • 有什么办法加快速度?因为链接的大小是 7000+
【解决方案2】:

在您尝试与所需元素进行交互之前,您必须为element_to_be_clickable() 诱导WebDriverWait,您可以使用以下任一Locator Strategy

import selenium
driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
titles=[]
for link in links:
  driver.get(link)
  data = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class = 'question-hyperlink']")))
  titles.append(data[0].text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    相关资源
    最近更新 更多