【问题标题】:How do I set headers using python's urllib?如何使用 python 的 urllib 设置标题?
【发布时间】:2011-12-17 12:27:15
【问题描述】:

我对 python 的 urllib 很陌生。我需要做的是为发送到服务器的请求设置一个自定义标头。具体来说,我需要设置 Content-type 和 Authorizations 标头。我已经查看了 python 文档,但我一直无法找到它。

【问题讨论】:

    标签: python http header urllib


    【解决方案1】:

    对于 Python 3 和 Python 2,这都有效:

    try:
        from urllib.request import Request, urlopen  # Python 3
    except ImportError:
        from urllib2 import Request, urlopen  # Python 2
    
    req = Request('http://api.company.com/items/details?country=US&language=en')
    req.add_header('apikey', 'xxx')
    content = urlopen(req).read()
    
    print(content)
    

    【讨论】:

    • 我们可以对请求做同样的事情吗 q.add_header('apikey', 'xxx')
    • 你是什么意思,@user3378649?
    • @user3378649 可能是你的意思是使用requests python 包custom headers
    • 这个答案 - 一千次是的(谢谢!)。我一直在努力寻找 python 2 和 3 的通用接口(在 urllib、urllib2 和 urllib3 之间)。
    【解决方案2】:

    使用urllib2添加HTTP头:

    来自文档:

    import urllib2
    req = urllib2.Request('http://www.example.com/')
    req.add_header('Referer', 'http://www.python.org/')
    resp = urllib2.urlopen(req)
    content = resp.read()
    

    【讨论】:

      【解决方案3】:

      使用 urllib2 并创建一个 Request 对象,然后将其交给 urlopen。 http://docs.python.org/library/urllib2.html

      我不再真正使用“旧”的 urllib。

      req = urllib2.Request("http://google.com", None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
      response = urllib2.urlopen(req).read()
      

      未经测试....

      【讨论】:

        【解决方案4】:

        对于多个标题,请执行以下操作:

        import urllib2
        req = urllib2.Request('http://www.example.com/')
        req.add_header('param1', '212212')
        req.add_header('param2', '12345678')
        req.add_header('other_param1', 'sample')
        req.add_header('other_param2', 'sample1111')
        req.add_header('and_any_other_parame', 'testttt')
        resp = urllib2.urlopen(req)
        content = resp.read()
        

        【讨论】:

          猜你喜欢
          • 2011-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-20
          相关资源
          最近更新 更多