Python 3 - 给urllib.request请求添加自定义头信息

19

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)' }
3个回答

40

可以通过先创建请求对象,然后将其提供给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文档


6
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


涉及到IT技术相关内容。
请放心,我会尽力让翻译更加通俗易懂。

2
#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()

请不要仅仅发布代码作为答案,还要提供代码的解释以及它是如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同。 - Ran Marciano

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接