【问题标题】:Python 3 - Add custom headers to urllib.request RequestPython 3 - 将自定义标头添加到 urllib.request 请求
【发布时间】:2018-04-12 06:15:36
【问题描述】:

Python 3 中,以下代码获取网页的 HTML 源代码。

import urllib.request
url = "https://docs.python.org/3.4/howto/urllib2.html"
response = urllib.request.urlopen(url)

response.read()

如何在使用 urllib.request 时将以下自定义标头添加到请求中?

headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' }

【问题讨论】:

    标签: python-3.x web-crawler python-requests urllib


    【解决方案1】:

    可以通过首先创建一个请求对象然后将其提供给 urlopen 来自定义请求标头。

    import urllib.request
    url = "https://docs.python.org/3.4/howto/urllib2.html"
    hdr = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' }
    
    req = urllib.request.Request(url, headers=hdr)
    response = urllib.request.urlopen(req)
    response.read()
    

    来源:Python 3.4 Documentation

    【讨论】:

      【解决方案2】:
      import urllib.request
      
      opener = urllib.request.build_opener()
      opener.addheaders = [('User-agent', 'Mozilla/5.0')]
      urllib.request.install_opener(opener)
      response = urllib.request.urlopen("url")
      response.read()
      

      如果您想了解详细信息可以参考python文档:https://docs.python.org/3/library/urllib.request.html

      【讨论】:

        【解决方案3】:
        #Using urllib.request, with urlopen, allows to open the specified URL.
        #Headers can be included inside the urlopen along with the url.
        
        from urllib.request import urlopen
        url = "https://docs.python.org/3.4/howto/urllib2.html"
        header = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' }
        response = urlopen(url, headers=header)
        response.read()
        

        【讨论】:

        • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
        猜你喜欢
        • 2016-11-14
        • 2017-12-14
        • 1970-01-01
        • 1970-01-01
        • 2013-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多