2. 携带表单参数,设置User-Agent,发送POST请求,文件上传
时间: 2024-05-06 16:19:49 浏览: 109
要发送带有表单参数的POST请求并上传文件,可以使用Python的requests库。
首先,创建一个包含表单参数的字典:
```python
data = {
'username': 'john',
'password': 'password123'
}
```
然后,创建一个包含文件信息的字典,其中键是文件名称,值是文件对象:
```python
files = {
'file': open('path/to/file.jpg', 'rb')
}
```
接下来,设置请求头中的User-Agent:
```python
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'
}
```
最后,使用requests库发送POST请求:
```python
import requests
response = requests.post('http://example.com/upload', data=data, files=files, headers=headers)
print(response.text)
```
这将向http://example.com/upload发送POST请求,包含表单参数data和文件信息files,并使用设置的User-Agent头。响应可以通过response.text属性进行访问。
阅读全文
相关推荐















