【问题标题】:proper way of implementing a user agent into a urllib.request.build_opener将用户代理实现到 urllib.request.build_opener 的正确方法
【发布时间】:2018-10-28 19:19:06
【问题描述】:

我正在尝试为我的 urllib 请求设置用户代理:

opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(cj),
            urllib.request.HTTPRedirectHandler(),
            urllib.request.ProxyHandler({'http': proxy})
)

最后:

response3 = opener.open("https://www.google.com:443/search?q=test", timeout=timeout_value).read().decode("utf-8")

将用户代理标头设置为的最佳方法是什么

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36

【问题讨论】:

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


    【解决方案1】:

    据我所知,对于urllib,我们有两个选择。

    build_opener 返回一个OpenerDirector 对象,该对象具有addheaders 属性。我们可以使用该属性更改用户代理和其他标头。

    opener.addheaders = [('User-Agent', 'My User-Agent')]
    
    url = 'http://httpbin.org/user-agent'
    r = opener.open(url, timeout=5)
    text = r.read().decode("utf-8")
    

    或者,我们可以使用install_opener 将OpenerDirector 对象安装到全局开启器并使用urlopen 提交请求。现在可以使用Request 来设置标题。

    urllib.request.install_opener(opener)
    
    url = 'http://httpbin.org/user-agent'
    headers = {'user-agent': "My User-Agent"}
    req = urllib.request.Request(url, headers=headers)
    r = urllib.request.urlopen(req, timeout=5)
    text = r.read().decode("utf-8")
    

    就个人而言,我更喜欢第二种方法,因为它更一致。一旦我们安装了开启程序,所有请求都将具有相同的处理程序,我们可以继续以相同的方式使用 urllib。但是,如果您不想对所有请求使用这些处理程序,则应选择第一种方法并使用addheaders 为特定的 OpenerDirector 对象设置标头。


    有了requests,事情就更简单了。

    如果我们想更改所有请求的用户代理或其他标头,我们可以使用session.heders 属性,

    s = requests.session()
    s.headers['user-agent'] = "My User-Agent"
    r = s.get(url, timeout=5)
    

    如果我们只想为特定请求设置标头,请使用headers 参数。

    headers = {'user-agent': "My User-Agent"}
    r = requests.get(url, headers=headers, timeout=5)
    

    【讨论】:

      猜你喜欢
      • 2015-03-11
      • 2013-07-31
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-03
      • 2010-09-21
      相关资源
      最近更新 更多