在Python爬虫中设置头部信息通常是为了模拟浏览器访问,避免被服务器识别为机器人。以下是使用`requests`库设置头部信息的方法:
1. 导入`requests`库。
import requests
2. 创建一个包含请求头信息的字典。
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.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/',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7',
'Accept-Encoding': 'gzip, deflate, br'
}
3. 使用`headers`参数向`requests.get()`或`requests.post()`方法中添加请求头。
response = requests.get('http://www.example.com', headers=headers)
以上代码示例展示了如何使用`requests`库设置请求头信息。请根据实际需要调整头部信息中的各个字段。