使用同一个IP去爬取同一个网站的网页,久了之后容易被屏蔽,这时候我们就需要代理服务器了,到这里http://www.xicidaili.com/ 我们可以查看到很多代理服务器地址。
在python的urllib库中,我们可以这样使用代理服务器访问我们需要访问的站点。
1 #使用代理服务器 2 import urllib.request 3 url = '我是url' 4 proxy = '代理服务地址:端口' 5 handle_proxy = urllib.request.ProxyHandler({'http':proxy}) 6 build_proxy = urllib.request.build_opener() 7 urllib.request.install_opener(build_proxy) 8 result = urllib.request.urlopen(url).read().encode('utf-8')
requests库使用代理
首先爬取代理,获得代理的列表
33 def get_proxy(url='http://api.xicidaili.com'): 34 requests.Encoding='utf-8' 35 header = { 36 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 37 'Accept-Encoding':'gzip, deflate', 38 'Accept-Language':'zh-CN,zh;q=0.9', 39 'Cache-Control':'max-age=0', 40 'Connection':'keep-alive', 41 'Cookie':'_free_proxy_session=BAh7B0kiD3Nlc3Npb25faWQGOgZFVEkiJTE1MWEzNGE0MzE1ODA3M2I3MDFkN2RhYjQ4MzZmODgzBjsAVEkiEF9jc3JmX3Rva2VuBjsARkkiMWZNM0MrZ0xic09JajRmVGpIUDB5Q29aSSs3SlAzSTM4TlZsLzNOKzVaQkE9BjsARg%3D%3D--eb08c6dcb3096d2d2c5a4bc77ce8dad2480268bd; Hm_lvt_0cf76c77469e965d2957f0553e6ecf59=1521984682; Hm_lpvt_0cf76c77469e965d2957f0553e6ecf59=1521984778', 42 'Host':'www.xicidaili.com', 43 'If-None-Match':'W/"df77cf304c5ba860bd40d8890267467b"', 44 'Referer':'http://www.xicidaili.com/api', 45 'Upgrade-Insecure-Requests':'1', 46 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.3' 47 } 48 response = requests.get(url=url,headers=header).content 49 selector = html.fromstring(response) 50 proxy_list = selector.xpath('//*[@id="ip_list"]/tr/td[2]/text()') 51 return proxy_list
请求中加入代理
20 proxy_list = get_proxy() 21 #使用代理并尝试请求,直到成功 22 while True: 23 proxy_ip = random.choice(proxy_list) 24 try: 25 response = requests.get(url=url,headers=header,proxies=proxy_ip)
26 break 27 except: 28 proxy_list.remove(proxy_ip) 29 continue