建立IP代理
在爬取豆瓣电影时,因为使用了多线程,导致IP被封,所以使用代理来爬取就很有必要了,本文主要是从西刺代理中爬取可以的IP,主要有以下几个功能:
1、获取西祠代理第一页高匿IP
2、使用代理IP访问网易网判断IP是否可能(使用多线程有效提升了验证速度)
3、可以在其他的爬虫中调用,如
- 1 from IPProxy import getProxy
- 2 ip_list = getProxy.ip_list_able
ip_list 即为获取的可用IP
源文件已放Github(https://github.com/createnewli/IPProxy),具体代码如下,欢迎交流讨论
- 1 # -*- coding: utf-8 -*-
- 2 # @Date : 2017-3-3 16:28:15
- 3 # @Author : youth-lee (you@example.org)
- 4 # @Link : http://www.cnblogs.com/youth-lee/
- 5 # @Version : Ver 0.1
- 6
- 7 \'\'\'
- 8 1、从西刺代理往上获取第一页国内高匿的IP
- 9 2、使用多线成检验获取的IP是否可在访问网易
- 10 3、可调用
- 11 from IPProxy import getProxy
- 12 ip_list = getProxy.ip_list_able
- 13 \'\'\'
- 14
- 15 import requests
- 16 import datetime
- 17 from bs4 import BeautifulSoup
- 18 from threading import Thread
- 19
- 20
- 21 class getProxy():
- 22 def __init__(self):
- 23 self.user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER"
- 24 self.header = {"User-Agent": self.user_agent}
- 25 self.start_url = "http://www.xicidaili.com/nn/"
- 26 self.ip_list = []
- 27 self.ip_list_able = []
- 28
- 29 self.get_ip()
- 30 self.check_ip_list()
- 31
- 32 print("获取了%s个可用代理" % len(self.ip_list_able))
- 33
- 34 def getContent(self, url):
- 35 # 获取网页内容并返回
- 36 content = requests.get(url, headers=self.header)
- 37 soup = BeautifulSoup(content.text, "lxml")
- 38 return soup
- 39
- 40 def get_ip(self):
- 41 soup = self.getContent(self.start_url)
- 42 tr_soup = soup.find("table", id="ip_list").find_all("tr")
- 43 # 把第一个tr标签剔除,第一个tr为标题行
- 44 tr_soup.pop(0)
- 45 for tr in tr_soup:
- 46 items = tr.find_all("td")
- 47
- 48 if items is not []:
- 49 ip = items[1].get_text().strip()
- 50 port = items[2].get_text().strip()
- 51 ip_port = ip + ":" + port
- 52 self.ip_list.append(ip_port)
- 53
- 54 def check_ip_list(self):
- 55 # 使用多线程检测ip是否可用
- 56 threads = []
- 57 for ip_port in self.ip_list:
- 58 t = Thread(target=self.check_ip, args=[ip_port])
- 59 t.start()
- 60 threads.append(t)
- 61
- 62 for t in threads:
- 63 t.join()
- 64
- 65 def check_ip(self, ip_port):
- 66 # 如果能正常访问则将ip放入到ip_list_able中
- 67 if self.is_Alive(ip_port):
- 68 self.ip_list_able.append(ip_port)
- 69
- 70 def is_Alive(self, ip_port):
- 71 # 使用代理IP去访问网易,能成功则能使用
- 72 proxy = {"http": ip_port}
- 73 test_url = "http://www.163.com"
- 74
- 75 try:
- 76 test_content = requests.get(
- 77 test_url, headers=self.header, proxies=proxy, timeout=1)
- 78 if test_content.status_code == 200:
- 79 # print("%s满足使用条件!" % (ip_port))
- 80 return True
- 81 else:
- 82 # print("%s不满足使用条件!" % (ip_port))
- 83 return False
- 84 except:
- 85 # print("%s不满足使用条件!" % (ip_port))
- 86 return False
- 87
- 88
- 89 if __name__ == "__main__":
- 90
- 91 time1 = datetime.datetime.now()
- 92
- 93 obj = getProxy()
- 94
- 95 print("获得%s个代理IP!" % len(obj.ip_list_able))
- 96
- 97 for ip in obj.ip_list_able:
- 98 print(ip)
- 99
- 100 time2 = datetime.datetime.now()
- 101 print("耗时:%s" % str(time2 - time1))
View Code