【问题标题】:Sending "User-agent" using Requests library in Python在 Python 中使用 Requests 库发送“用户代理”
【发布时间】:2012-05-15 17:48:44
【问题描述】:

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

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

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

是否可以在标头中发送此信息?如果没有,我该如何发送?

【问题讨论】:

    标签: python web-crawler python-requests


    【解决方案1】:

    user-agent 应指定为标题中的字段。

    这是list of HTTP header fields,您可能会对request-specific fields 感兴趣,其中包括User-Agent

    如果您使用 requests v2.13 及更新版本

    最简单的方法是创建一个字典并直接指定标题,如下所示:

    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 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)
    

    【讨论】:

    • 您还可以访问您使用 response.request.headers 发送的标头,这是因为原始请求对象是响应对象的一个​​属性。另见http://docs.python-requests.org/en/latest/user/advanced/#request-and-response-objects
    • 默认值也可以作为 requests.utils.default_user_agent() 如果你想用你自己的信息来增加它。
    • 不正确。它破坏了其余的标题。他应该从 requests.utils.default_user_agent() 获取默认值的副本并对其进行更新,然后发送。
    • 为方便起见,在httpbin.org/headers(可下载的东西)上,您可以获得浏览器标题,然后让您的查询出现
    • 至少在2.13.0 中,标题不会被破坏,docs 只是告诉您使用headers kwarg。
    【解决方案2】:

    使用session更方便,这样你就不用每次都记得设置headers了:

    session = requests.Session()
    session.headers.update({'User-Agent': 'Custom user agent'})
    
    session.get('https://httpbin.org/headers')
    

    默认情况下,会话还为您管理 cookie。如果您想禁用它,请参阅this question

    【讨论】:

      【解决方案3】:

      您可以像下面这样操作:

      import requests
      
      url = requests.post("URL", headers={"FUser":"your username","FPass":"your password","user-agent": "your custom text for the user agent "})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多