python - 将用户代理实现到 urllib.request.build_opener 的正确方法

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

我正在尝试为我的 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")

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

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

最佳答案

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

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

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 来设置 header 。

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

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

<小时/>

requests事情更简单了。

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

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

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

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

关于python - 将用户代理实现到 urllib.request.build_opener 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53035241/

相关文章:

python - 嵌套字典语法

python - 在 Python 请求 get 或 post 方法上干净地设置 max_retries

python - 从 cookie 中提取 Httponly、Secure、域和路径

python - 创建 3D 圆锥体或圆盘并使用 matplotlib 不断更新其对称轴

python-3.x - 从 scikit 数组转换为 PIL photoimage 的图像被扭曲

python - 如何使用 Pandas 将一列与另外两列中的唯一值求和?

python - Paramiko 有时会引发 'AuthenticationException'

python - 从 Python URL 中提取特定文本

python - ValueError : Error when checking input: expected lstm_1_input to have shape (973, 215) 但得到形状为 (61, 215) 的数组

python - 从 Python 程序响应 git 命令行提示符