【发布时间】:2019-04-07 18:55:53
【问题描述】:
我正在使用 python 从 URL 的多个页面中获取 HTML 数据。我发现当 URL 不存在时 urllib 会抛出异常。如何检索该自定义 404 错误页面的 HTML(显示“找不到页面”之类的页面。)
当前代码:
try:
req = Request(URL, headers={'User-Agent': 'Mozilla/5.0'})
client = urlopen(req)
#downloading html data
page_html = client.read()
#closing connection
client.close()
except:
print("The following URL was not found. Program terminated.\n" + URL)
break
【问题讨论】:
-
见
HTTPError。它有一个返回响应内容的.read()方法。
标签: python python-3.x exception web-scraping beautifulsoup