掌握设置请求头的方法
课程位置:06.爬虫模拟浏览器客户端.pdf - 6.1 请求头
常用请求头:
User-Agent - 浏览器标识,用于识别客户端类型Referer - 请求来源,用于防盗链Cookie - 用户身份信息检测到的User-Agent:Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
检测到的Referer:
请设置正确的Referer(包含/practice或localhost)
import requests
url = 'https://req.haleibc.com/practice5'
# 设置请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Referer': 'https://req.haleibc.com/practice'
}
response = requests.get(url, headers=headers)
print(response.text)
1. 设置User-Agent为常见浏览器标识
2. 设置Referer为练习列表页面
3. 同时设置两个请求头并验证