1. 程式人生 > >利用Python爬取可用的代理IP

利用Python爬取可用的代理IP

strip() color 地址 read main urn try exc head

前言

就以最近發現的一個免費代理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]+"\t"+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("\t") 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]+\n) 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地址,如有需要,可以多爬取幾頁。同時,該網站是時時更新的,建議爬取時只爬取前幾頁的即可。

利用Python爬取可用的代理IP