在Python中,设置请求头通常使用`requests`库,可以通过以下步骤进行操作:
1. 导入`requests`库。
3. 在发送HTTP请求时,将这个字典作为`headers`参数传入。
import requests
创建请求头字典
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Referer': 'http://www.baidu.com/'
}
发送GET请求,并传入请求头
url = 'https://www.example.com'
response = requests.get(url, headers=headers)
打印响应内容
print(response.text)
在这个例子中,我们设置了一些常见的请求头,如`User-Agent`、`Accept`、`Cache-Control`、`Connection`和`Referer`。这些请求头可以模拟常见的浏览器行为,有助于通过某些网站的访问限制。