Python爬虫中的网页请求与响应错误示例

原创 川长思鸟来 2025-01-11 02:18 56阅读 0赞

在Python的网络爬虫中,常见的网页请求与响应错误主要包括以下几个示例:

  1. HTTP请求错误

    • URLError:如果URL本身有误(如无效链接、编码问题等),会抛出此异常。
      ```python
      import requests

    try:

    1. response = requests.get('http://example.com/invalid') # 错误的URL
    2. print(response.text)

    except requests.RequestException as e:

    1. print(f"Error occurred: {e}")

    ```

  2. HTTP状态码错误

    • HTTPStatus:Python标准库中的httpstatus模块提供了一系列HTTP状态码,例如404表示找不到资源。
      ```python
      import httpstatus

    try:

    1. response = requests.get('http://example.com/invalid') # 错误的URL
    2. if response.status_code == httpstatus.HTTPStatus.NOT_FOUND: # 检查是否为404状态码
    3. print("Resource not found.")
    4. else:
    5. print(f"Response status code: {response.status_code}")

    except requests.RequestException as e:

    1. print(f"Error occurred: {e}")

    ```

  3. 网络连接错误

    • ConnectionError:Python的内置异常,表示在尝试连接时发生了错误。
      1. try:
      2. response = requests.get('http://example.com/invalid') # 错误的URL
      3. print(response.text)
      4. except (requests.RequestException, ConnectionError)) as e:
      5. print(f"Error occurred: {e}")

以上就是Python爬虫中常见的网页请求与响应错误示例。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,56人围观)

还没有评论,来说两句吧...

相关阅读