python request库用法

Python的`requests`库是一个非常流行的HTTP客户端库,它允许你轻松地发送HTTP请求。以下是`requests`库的一些基本用法:

### 安装`requests`库

如果你还没有安装`requests`库,你可以通过pip安装它:

```bash
pip install requests
```

### 发送GET请求

```python
import requests

# 发送GET请求
response = requests.get('https://api.example.com/data')

# 检查请求是否成功
if response.status_code == 200:
    # 处理响应内容
    data = response.json()  # 假设响应内容是JSON格式
    print(data)
else:
    print('请求失败,状态码:', response.status_code)
```

### 发送POST请求

```python
import requests

# 发送POST请求
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com/submit', data=payload)

# 检查请求是否成功
if response.status_code == 200:
    print('数据提交成功')
else:
    print('请求失败,状态码:', response.status_code)
```

### 发送带有Headers的请求

```python
import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

response = requests.get('https://api.example.com/data', headers=headers)
print(response.text)
```

### 发送带有认证的请求

```python
import requests

url = 'https://api.example.com/protected'
response = requests.get(url, auth=('username', 'password'))
print(response.text)
```

### 发送带有Cookies的请求

```python
import requests

url = 'https://api.example.com/cookie'
cookies = {'cookie_name': 'cookie_value'}
response = requests.get(url, cookies=cookies)
print(response.text)
```

### 发送带有Timeout的请求

```python
import requests

try:
    response = requests.get('https://api.example.com/data', timeout=5)  # 设置5秒超时
    print(response.text)
except requests.exceptions.Timeout:
    print('请求超时')
```

### 上传文件

```python
import requests

files = {'file': open('report.xls', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)
print(response.text)
```

`requests`库提供了一个简单易用的API来发送各种HTTP请求,并且它还支持会话(Sessions)、持久连接、保持Cookies等高级功能。以上只是一些基本用法,`requests`库的功能非常强大,你可以通过阅读官方文档来了解更多高级用法。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值