使用Python的Requests库发送“User-agent”

342

我想在使用Python Requests请求网页时,发送一个"User-agent"的值。我不确定是否可以将其作为头文件的一部分发送,例如下面的代码:

debug = {'verbose': sys.stderr}
user_agent = {'User-agent': 'Mozilla/5.0'}
response  = requests.get(url, headers = user_agent, config=debug)

调试信息没有显示请求期间发送的标头。

在标头中发送这些信息是否可以接受?如果不行,我该如何发送它们?

3个回答

478

在请求头中应将user-agent指定为一个字段。

这里有一个HTTP头字段列表,你可能会对请求特定的字段感兴趣,其中包括User-Agent

如果您使用的是requests v2.13及更高版本

实现您想要的最简单的方法是创建一个字典并直接指定您的头部,如下所示:

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': 'youremail@domain.example'  # This is another valid field
}

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

如果您使用的是requests v2.12.x及更早版本

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)

7
您可以通过 response.request.headers 访问您发送的请求头信息,这是因为响应对象中包含了原始请求对象的属性。请参见http://docs.python-requests.org/en/latest/user/advanced/#request-and-response-objects。 - here
5
如果您想要仅使用自己的信息来增强默认用户代理,则可以使用requests.utils.default_user_agent()函数,该函数也提供了默认值。 - nealmcb
3
这不正确,它会覆盖其余的标头。他应该从requests.utils.default_user_agent()获取默认值的副本并进行更新,然后发送那些值。 - Chad Miller
2
为了方便,您可以在 https://httpbin.org/headers(可下载的内容)中获取浏览器标头,然后使您的查询出现。 - m3nda
1
至少在2.13.0版本中,头部不会被覆盖,文档只是告诉你使用headers关键字参数。 - Jmills

99

使用会话(session)更方便,这样你就不必每次都记得设置标头:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

默认情况下,会话还会为您管理 cookie。如果您想要禁用它,请参见此问题


12
它会像浏览器一样发送请求。
import requests

url = 'https://Your-url'
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'}

response= requests.get(url.strip(), headers=headers, timeout=10)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接