python爬虫浏览器伪装

#导入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")#创建一个openeropener=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')

设置代理

#定义代理ipproxy_addr="122.241.72.191:808"#设置代理proxy=urllib.request.ProxyHandler({'http':proxy_addr})#创建一个openeropener=urllib.request.build_opener(proxy)#将opener安装为全局urllib.request.install_opener(opener)#用urlopen打开网页data=urllib.request.urlopen(url).read().decode('utf-8','ignore')

同时设置用代理和模拟浏览器访问

#定义代理ipproxy_addr="122.241.72.191:808"#创建一个请求req=urllib.request.Request(url)#添加headersreq.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)#创建一个openeropener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)#将opener安装为全局urllib.request.install_opener(opener)#用urlopen打开网页data=urllib.request.urlopen(req).read().decode('utf-8','ignore')

获取代理ip

# 爬取首页代理IP地址# Python学习交流群:711312441from bs4 import BeautifulSoupimport requestsimport random# 获取首页IP列表def get_ip_list(url, headers):    web_data = requests.get(url, headers=headers)    soup = BeautifulSoup(web_data.text, 'lxml')    ips = soup.find_all('tr')    ip_list = []    # 提取ip列表    # range()的用法:range(1,5) #代表从1到5(不包含5)    for i in range(1, len(ips)):        ip_info = ips[i]        tds = ip_info.find_all('td')        ip_list.append(tds[5].text.lower() + '://' + tds[1].text + ':' + tds[2].text)    return ip_list# 随机获取一个ipdef get_random_ip(ip_list):    # 随机获取一个ip(从返回的ip列表里面)    proxy_ip = random.choice(ip_list)    return proxy_ip# 测试if __name__ == '__main__':    # 国内高匿代理IP    url = 'http://www.xicidaili.com/nn/'    headers = {        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'    }    # 获取首页ip列表    ip_list = get_ip_list(url, headers=headers)    # 随机提取一个ip    ip = get_random_ip(ip_list)    print('代理ip地址:' + ip)