python3中,requests模块的相关异常

一、前言

要调用requests模块的内置异常,只要“from requests.exceptions import xxx”就可以了,
比如:

from requests.exceptions import ConnectionError, ReadTimeout

或者:

from requests import ConnectionError, ReadTimeout

二、requests模块内置异常类的层次结构如下:

IOError
 +-- RequestException  # 处理不确定的异常请求
      +-- HTTPError  # HTTP错误
      +-- ConnectionError  # 连接错误
      |    +-- ProxyError  # 代理错误
      |    +-- SSLError  # SSL错误
      |    +-- ConnectTimeout(+-
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
requests是Python一个常用的HTTP库,用于向Web服务器发送HTTP/1.1请求。 使用requests模块,可以方便地进行GET、POST等请求,并处理响应结果。 以下是requests模块的基本用法: 1. 安装requests模块:在命令行输入 pip install requests。 2. 发送GET请求: ```python import requests url = 'http://www.example.com' response = requests.get(url) print(response.text) ``` 3. 发送带参数的GET请求: ```python import requests url = 'http://www.example.com' params = {'key1': 'value1', 'key2': 'value2'} response = requests.get(url, params=params) print(response.text) ``` 4. 发送POST请求: ```python import requests url = 'http://www.example.com' data = {'key1': 'value1', 'key2': 'value2'} response = requests.post(url, data=data) print(response.text) ``` 5. 发送带文件的POST请求: ```python import requests url = 'http://www.example.com' files = {'file': open('example.txt', 'rb')} response = requests.post(url, files=files) print(response.text) ``` 6. 发送带headers的请求: ```python import requests url = 'http://www.example.com' headers = {'User-Agent': 'Mozilla/5.0'} response = requests.get(url, headers=headers) print(response.text) ``` 7. 处理异常: ```python import requests url = 'http://www.example.com' try: response = requests.get(url, timeout=1) response.raise_for_status() except requests.exceptions.RequestException as e: print(e) ``` 以上就是requests模块的基本用法。更多高级用法可以查看官方文档:https://requests.readthedocs.io/en/latest/。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值