获取User-Agent:
用浏览器打开任意页面,按一下F12,点击Network即可找到User-Agent对应信息
1、使用build.opener()修改报头
headers=("User-Agent",“Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36”)
opener=urllib.request.build_opener()
opener.addheaders=[headers]
data=opener.open(url).read()
2、使用add_header()添加报头
header="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
req=urllib.request.Request(url)
req.add_header('User-Agent',header)
data=urllib.request.urlopen(req).read()