温馨提示×

python requests爬虫请求头怎样设置

小樊
100
2024-12-08 15:48:20
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python的requests库中,设置请求头(headers)非常简单。你可以通过传递一个字典给headers参数来实现。以下是一个简单的示例:

import requests

url = 'https://api.example.com/data'
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',
    'Authorization': 'Bearer your_access_token',
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}

response = requests.get(url, headers=headers)

print(response.text)

在这个示例中,我们设置了一些常见的请求头,如User-AgentAuthorizationAcceptContent-Type。你可以根据需要添加或修改这些请求头。请注意,有些网站可能会检查请求头,以确保它们来自合法的客户端。在这种情况下,你可能需要使用更复杂的请求头来模拟浏览器行为。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python爬虫requests如何设置请求头

0