前言
就以最近发现的一个免费代理IP网站为例:http://www.xicidaili.com/nn/。在使用的时候发现很多IP都用不了。
所以用Python写了个脚本,该脚本可以把能用的代理IP检测出来。
1 #encoding=utf8 2 import urllib2 3 from bs4 import BeautifulSoup 4 import urllib 5 import socket 6 7 User_Agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0' 8 header = {} 9 header['User-Agent'] = User_Agent 10 11 ''' 12 获取所有代理IP地址 13 ''' 14 def getProxyIp(): 15 proxy = [] 16 for i in range(1,2): 17 try: 18 url = 'http://www.xicidaili.com/nn/'+str(i) 19 req = urllib2.Request(url,headers=header) 20 res = urllib2.urlopen(req).read() 21 soup = BeautifulSoup(res) 22 ips = soup.findAll('tr') 23 for x in range(1,len(ips)): 24 ip = ips[x] 25 tds = ip.findAll("td") 26 ip_temp = tds[1].contents[0]+" "+tds[2].contents[0] 27 proxy.append(ip_temp) 28 except: 29 continue 30 return proxy 31 32 ''' 33 验证获得的代理IP地址是否可用 34 ''' 35 def validateIp(proxy): 36 url = "http://ip.chinaz.com/getip.aspx" 37 f = open("E:ip.txt","w") 38 socket.setdefaulttimeout(3) 39 for i in range(0,len(proxy)): 40 try: 41 ip = proxy[i].strip().split(" ") 42 proxy_host = "http://"+ip[0]+":"+ip[1] 43 proxy_temp = {"http":proxy_host} 44 res = urllib.urlopen(url,proxies=proxy_temp).read() 45 f.write(proxy[i]+' ') 46 print proxy[i] 47 except Exception,e: 48 continue 49 f.close() 50 51 52 if __name__ == '__main__': 53 proxy = getProxyIp() 54 validateIp(proxy)
总结
这只是爬取的第一页的IP地址,如有需要,可以多爬取几页。同时,该网站是时时更新的,建议爬取时只爬取前几页的即可。