【问题标题】:Using headers with the Python requests library's get method将标头与 Python 请求库的 get 方法一起使用
【发布时间】:2011-09-09 18:25:39
【问题描述】:

所以我最近偶然发现了这个在 Python 中处理 HTTP 请求的优秀库;在这里找到http://docs.python-requests.org/en/latest/index.html

我喜欢使用它,但我不知道如何在我的 get 请求中添加标头。帮忙?

【问题讨论】:

    标签: python http-request python-requests


    【解决方案1】:

    根据API,headers都可以用requests.get()传入:

    import requests
    r=requests.get("http://www.example.com/", headers={"Content-Type":"text"})
    

    【讨论】:

    • 您可以检查发送的http请求标头:print(r.request.headers)
    【解决方案2】:
    1. 转到http://myhttpheader.com

    2. 复制属性 - 通常是“Accept-Language”和“User-Agent”。

    3. 将它们包装在字典中:

      headers = { 'Accept-Language' : content-copied-from-myhttpheader,
                  'User-Agent':content-copied-from-myhttpheader}
      
    4. 在您的请求中传递标头

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

    【讨论】:

      【解决方案3】:

      This answer 告诉我你可以为整个会话设置标题:

      s = requests.Session()
      s.auth = ('user', 'pass')
      s.headers.update({'x-test': 'true'})
      
      # both 'x-test' and 'x-test2' are sent
      s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
      

      奖金:Sessions also handle cookies.

      【讨论】:

        【解决方案4】:

        根据您链接的页面上的docs(强调我的),看起来很简单。

        requests.get(url, params=None, headers=None, cookies=None, auth=None, 超时=无)

        发送一个 GET 请求。 返回Response 对象。

        参数:

        • url – 新的 URL Request 对象。
        • 参数 –(可选) 要发送的 GET 参数字典 与Request
        • 标题 - (可选) 要发送的 HTTP 标头字典 Request
        • cookies –(可选) 要发送的 CookieJar 对象 Request
        • auth –(可选)AuthObject 启用基本 HTTP 身份验证。
        • 超时 - (可选)描述 请求超时。

        【讨论】:

          猜你喜欢
          • 2018-08-14
          • 1970-01-01
          • 1970-01-01
          • 2021-01-11
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          • 2019-06-15
          相关资源
          最近更新 更多