代理ip池的建立

国内免费的代理ip地址,http://www.xicidaili.com/nn/

源代码如下:

import urllib2  

from bs4 import BeautifulSoup  

import csv  

def IPspider(numpage):  

 csvfile = file('ips.csv''wb')    

 writer = csv.writer(csvfile)  

 url='http://www.xicidaili.com/nn/'  

 user_agent='IP'  

 headers={'User-agent':user_agent}  

 for num in xrange(1,numpage+1):  

 ipurl=url+str(num)  

 print 'Now downloading the '+str(num*100)+' ips'  

 request=urllib2.Request(ipurl,headers=headers)  

content=urllib2.urlopen(request).read()  

 bs=BeautifulSoup(content,'html.parser')  

 res=bs.find_all('tr')  

 for item in res:  

try:  

 temp=[] 

 tds=item.find_all('td')  

temp.append(tds[1].text.encode('utf-8'))  

 temp.append(tds[2].text.encode('utf-8'))  

writer.writerow(temp)  

except IndexError:  

pass  

IPspider(10)  

这样就爬到了1000个代理IP和端口,并不是所有的代理IP都可以用,需要检查一下哪些IP是可以使用的。连上代理后能不能在2秒内打开百度的页面,如果可以,则认为IP可用,添加到一个list里供后面备用,实现代码如下。

import socket  

def IPpool():  

 socket.setdefaulttimeout(2)  

 reader=csv.reader(open('ips.csv'))  

    IPpool=[]  

    for row in reader:  

        proxy=row[0]+':'+row[1]  

        proxy_handler=urllib2.ProxyHandler({"http":proxy})  

        opener=urllib2.build_opener(proxy_handler)  

        urllib2.install_opener(opener) 

        try:  

            html=urllib2.urlopen('http://www.baidu.com')  

            IPpool.append([row[0],row[1]])  

        except Exception,e:  

            continue  

    return IPpool  

猜你喜欢

转载自blog.csdn.net/qq_31032181/article/details/79164851