【问题标题】:How to get HTML content of 404 error page using python?如何使用 python 获取 404 错误页面的 HTML 内容?
【发布时间】: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


【解决方案1】:

您尝试过requests 库吗?

只需使用 pip 安装库

pip install requests

并像这样使用它

import requests

response = requests.get('https://stackoverflow.com/nonexistent_path')
print(response.status_code) # 404
print(response.text) # Prints the raw HTML response

【讨论】:

    猜你喜欢
    • 2011-11-24
    • 2012-10-12
    • 2021-08-12
    • 1970-01-01
    • 2021-10-14
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    相关资源
    最近更新 更多