Answers:
的user-agent
应指定为在报头中的字段。
这是HTTP标头字段的列表,您可能会对特定于请求的字段感兴趣,其中包括User-Agent
。
执行所需操作的最简单方法是创建字典并直接指定标题,例如:
import requests
url = 'SOME URL'
headers = {
'User-Agent': 'My User Agent 1.0',
'From': 'youremail@domain.com' # This is another valid field
}
response = requests.get(url, headers=headers)
旧版本的requests
默认标头已损坏,因此您需要执行以下操作来保留默认标头,然后向其添加自己的标头。
import requests
url = 'SOME URL'
# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()
# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
{
'User-Agent': 'My User Agent 1.0',
}
)
response = requests.get(url, headers=headers)
response.request.headers
,因为原始请求对象是响应对象的属性,所以可以使用。另见http://docs.python-requests.org/en/latest/user/advanced/#request-and-response-objects