python-3.x - 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 循环?
解决方案
如果出现异常,您应该使用try-except
and 继续下一次迭代。
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
推荐阅读
- asp.net-mvc - 在 ASP.Net MVC 项目上设置实体框架(代码优先)的问题
- c++ - 在 C++ 中用递归填充 D2 数组,有时工作正常,抛出异常
- c# - 如何使用 iOS 共享扩展从使用 Xamarin 表单的照片应用程序中检索图像?
- c# - 我无法在 Entity Framework Core 中播种数据
- spring - sun.security.validator.ValidatorException:找不到受信任的证书 - Spring Boot
- c# - 如何比较除空属性之外的两个对象?
- docker - docker --rm 仅当退出代码为零时
- c++ - C++ WinINET FtpPutFile 错误代码 3
- angular - 我在哪里可以下载特定版本的 d3.js 用于 Angular?
- python - 从文件索引字典