【问题标题】:Problem with scraping multiple pages with selenium webdriver - python使用 selenium webdriver 抓取多个页面的问题 - python
【发布时间】:2021-08-03 07:26:37
【问题描述】:

我正在尝试抓取网页和该网页中的链接。网页为:https://webgate.ec.europa.eu/rasff-window/screen/list。如果您注意到大约有 6000 多个通知,并且这些通知具有与之关联的单独链接。我想将所有链接存储在列表中。我正在使用以下代码执行此操作:

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

import time

from webdriver_manager.chrome import ChromeDriverManager


d = webdriver.Chrome(ChromeDriverManager().install())

#trying this scraping for multiple pages
links = []
i = 1
elems = d.find_elements_by_xpath("//a[@href]")
for elem in elems:
    link_list = elem.get_attribute("href")
    links.append(link_list)

while True:

  print("This is the now the {} page".format(i))
  i +=1
  time.sleep(1)
  try:
    time.sleep(0.5)
    WebDriverWait(d, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[@aria-label='Next page']"))).click()
    print("we have clicked it once")
    time.sleep(0.9)
    
    elems2 = d.find_elements_by_xpath("//a[@href]")
    for elem2 in elems2:
        link_list = elem2.get_attribute("href")
        links.append(link_list)
    print("The button is clickable")
    time.sleep(1)
  except:
    print("The button is now not clickable, we have collected all the links")
    break

这个想法是使用 selenium 首先从该页面中找到所有 href 链接,然后单击下一页按钮并执行相同的操作,我的 While 循环就是这样做的。但是当我运行这段代码时,它并没有完成整个循环。例如:如果有大约 6400 条通知,我希望它会运行到第 64 页,但它会停在中间,表明下一个按钮不可点击(条件除外),尽管实际上该按钮是可点击的。这发生在随机页面上,我也尝试过更改 time.sleep。我做错了什么吗?

【问题讨论】:

  • 您应该在浏览器中检查您在 HTML 中获得的内容。当元素被其他元素隐藏(如弹出消息)或在窗口中不可见时(需要使用 JavaScript 或使用ActionChain 滚动窗口),元素可以是不可点击的。您应该观察何时出现错误并查看此时浏览器中的内容。
  • 最大的错误是except: - 你应该使用except Exception as ex: print(ex) 来查看真正的问题。
  • 你忘了d.get(url)

标签: python selenium-webdriver web-scraping selenium-chromedriver


【解决方案1】:

我检查了来自异常的消息

except Exception as ex: 
     print(ex)

它表明问题不是button,而是href

似乎有时它会在 JavaScript 更新页面上的所有元素之前获得对 <a> 的引用 - 然后当它尝试从 <a> 获取 href 时,错误显示此 <a> 不存在在页面上,因为同时JavaScript 将其删除并放入新的<a>

并且检查按钮是否可点击可能没用,因为它一直存在。

在收到<a> 之前,您应该睡得更久。或者您会找到更好的方法来检测您是否获得了新的引用或与以前相同。

【讨论】:

  • 感谢@furas,在看到异常后,我才知道我的实际问题是什么,这是您在答案中正确指出的陈旧元素问题。增加 time.sleep 确实帮助我解决了这个问题。我会接受答案。
猜你喜欢
  • 2019-06-04
  • 2019-11-17
  • 1970-01-01
  • 2021-11-02
  • 2020-09-13
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多