python requests 请求头部
时间: 2023-10-18 18:06:12 浏览: 40
在使用Python的requests库发送请求时,可以通过设置headers参数来添加请求头部信息。请求头部中包含了一些与请求相关的信息,比如User-Agent、Accept-Language等。下面是一个示例代码,演示了如何设置请求头部:
```python
import requests
url = 'https://www.example.com'
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',
'Accept-Language': 'en-US,en;q=0.9',
'Referer': 'https://www.google.com/'
}
response = requests.get(url, headers=headers)
```
在上面的示例中,我们通过设置headers参数来设置请求头部信息。其中,'User-Agent'代表用户代理,模拟浏览器的身份进行请求;'Accept-Language'代表接受的语言类型;'Referer'代表请求的来源页面。
相关问题
requests python头部请求
requests是一个基于python语言开发的开源库,用于进行基于HTTP协议的接口测试。使用requests发送请求时,可以使用get、post、put、delete等方法进行不同类型的请求。例如,通过requests.get()方法发送get请求,通过requests.put()方法发送put请求,通过requests.delete()方法发送delete请求。在发送请求时,还可以设置请求头信息,通过headers参数传入。可以使用requests.get()方法的params参数来传递URL参数。接收到响应后,可以使用response.text来获取响应内容,可以使用response.encoding来设置响应编码。
python requests post请求
使用 Python 的 requests 库发送 POST 请求非常简单,下面是一个示例代码:
```
import requests
url = 'http://example.com/api/endpoint'
data = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-type': 'application/json'}
response = requests.post(url, json=data, headers=headers)
print(response.status_code)
print(response.json())
```
这段代码会向 http://example.com/api/endpoint 发送一个 POST 请求,请求体包含 JSON 格式的 key1 和 key2,Content-type 头部设置为 application/json。
如果你想发送表单数据,可以使用 data 参数来代替 json 参数,并且 Content-type 头部设置为 application/x-www-form-urlencoded。
```
import requests
url = 'http://example.com/api/endpoint'
data = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-type': 'application/x-www-form-urlencoded'}
response = requests.post(url, data=data, headers=headers)
print(response.status_code)
print(response.json())
```