https://www.jb51.net/article/139587.htm
python爬虫浏览器伪装
1.
#导入urllib.request模块
import urllib.request
#设置请求头
headers=("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0")
#创建一个opener
opener=urllib.request.build_opener()
#将headers添加到opener中
opener.addheaders=[headers]
#将opener安装为全局
urllib.request.install_opener(opener)
#用urlopen打开网页
data=urllib.request.urlopen(url).read().decode(‘utf-8‘,‘ignore‘)
2.
#定义代理ip
proxy_addr="122.241.72.191:808"
#设置代理
proxy=urllib.request.ProxyHandle({‘http‘:proxy_addr})
#创建一个opener
opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandle)
#将opener安装为全局
urllib.request.install_opener(opener)
#用urlopen打开网页
data=urllib.request.urlopen(url).read().decode(‘utf-8‘,‘ignore‘)
#定义代理ip
proxy_addr="122.241.72.191:808"
#创建一个请求
req=urllib.request.Request(url)
#添加headers
req.add_header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
#设置代理
proxy=urllib.request.ProxyHandle("http":proxy_addr)
#创建一个opener
opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandle)
#将opener安装为全局
urllib.request.install_opener(opener)
#用urlopen打开网页
data=urllib.request.urlopen(req).read().decode(‘utf-8‘,‘ignore‘)
原文:https://www.cnblogs.com/tao-yuan/p/10409459.html