在python获取网页的代码中添加头信息模拟浏览器

你说的曾经没有我的故事 提交于 2019-12-04 17:51:49

方法1:使用build_opener()来添加

import urllib2
url = "https://www.baidu.com"
headers = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
opener = urllib2.build_opener()
opener.addheaders = [headers]
file = opener.open(url)
html = file.read()
print html

方法2:利用add_header()来添加

import urllib2
url = "https://blog.51cto.com/lsfandlinux/2046467"
req = urllib2.Request(url)
req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
file = urllib2.urlopen(req)
html = file.read()
print html

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!