首页 > 解决方案 > Selenium 由于错误而无法加载链接时如何跳转到新网站?

问题描述

我有一个大约 13.000 个网站的列表。从这些链接中的每一个,我打算通过 Python、Beautiful Soup 和 Selenium 一个一个地抓取信息。

对于大多数网站,抓取过程都可以正常工作。但是,Selenium 偶尔会遇到特定链接的问题。例如,它在加载其中之一时给出了以下错误消息:

WebDriverException: Message: unknown error: net::ERR_SSL_BAD_RECORD_MAC_ALERT (Session info: chrome=90.0.4430.93)

当我去驱动程序并手动重新加载页面时,它运行良好。不幸的是,该错误停止了整个抓取过程。当我再次运行该过程时,我希望防止这种情况再次发生。

这是我用来抓取链接的循环的第一部分:

for house in all_nd:
    if str(requests.head(house)) == '<Response [200]>':
        driver.get(house)
        
        house_html = driver.page_source
        house_soup = BeautifulSoup(huis_html)  

在这里,all_nd 是一个 Python 3 列表,其中包含房屋和公寓的网站字符串。它们都以“https://”开头。

问题

如何确保抓取过程不会因网站的(临时)错误而停止?如何跳转到列表中的下一个链接并继续 for 循环?

标签: python-3.xseleniumselenium-webdriverbeautifulsoupselenium-chromedriver

解决方案


如果出现异常,您应该使用try-exceptand 继续下一次迭代。

for house in all_nd:
  try:
    if str(requests.head(house)) == '<Response [200]>':
        driver.get(house)
        
        house_html = driver.page_source
        house_soup = BeautifulSoup(huis_html)  
  except:
    continue

推荐阅读