【发布时间】: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