【问题标题】:Python: Selenium desn't find element when it is available [duplicate]Python:Selenium 在可用时找不到元素 [重复]
【发布时间】:2020-07-31 20:45:18
【问题描述】:

我正在尝试抓取一个网站,我正在使用以下代码:

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

我在 google colab 上运行此代码。我得到的问题是循环迭代某些值后数据不存储任何值。如果我重新启动内核并重新运行代码,那么代码对于较早的迭代工作正常,并且在另一个迭代中会出现同样的问题。我很困惑为什么会这样。我尝试了很多东西,但没有任何效果。另外,链接的大小很大,有什么办法可以加快速度吗?

编辑:添加了完整代码的链接: https://colab.research.google.com/drive/1SYIA_SUPYzlR-K9ph4grNem-LbL61uB7?usp=sharing

【问题讨论】:

    标签: python selenium selenium-chromedriver


    【解决方案1】:

    在循环之上,可以设置驱动的隐式等待时间:

    driver.implicitly_wait(10) # 10 seconds for any element
    

    这类似于@XRayCat 的回答。

    【讨论】:

      【解决方案2】:

      尝试使用WebDriverWait(driver, 10).until(data) 代替 time.sleep(0.5)。这会等待元素出现十秒钟。

      【讨论】:

      • 但是链接的大小是7000+所以等10秒会不会太久?
      • 现在,我收到了一个以前没有的新错误,Message: stale element reference: element is not attached to the page document。我该怎么办?
      • 如果在 for 循环中移动 driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options) 会出现同样的错误吗?
      • 你也可以尝试使用:from selenium.webdriver.support import expected_conditions as C C.element_to_be_clickable
      猜你喜欢
      • 2023-03-28
      • 2020-04-19
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      相关资源
      最近更新 更多