python随机生成请求头
时间: 2023-11-04 10:00:33 浏览: 37
可以使用 Python 中的 requests 库来随机生成请求头,示例代码如下:
```python
import requests
import random
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36',
]
headers = {
'User-Agent': random.choice(user_agents),
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
}
url = 'http://www.example.com'
response = requests.get(url, headers=headers)
```
以上代码中,我们定义了一个 user_agents 列表,包含了几个常用的浏览器信息。然后随机选择一个作为请求头中的 User-Agent 字段。其他字段也可以类似的方式添加。最后使用 requests 库的 get 方法发送请求,传入 headers 参数即可。