在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 时如何将以下自定义 header 添加到请求中?
headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' }
最佳答案
可以通过首先创建请求对象然后将其提供给 urlopen 来自定义请求 header 。
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.x - Python 3 - 将自定义 header 添加到 urllib.request 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47029280/