python使用代理抓取网站图片(多线程)

一、功能说明:1. 多线程方式抓取代理服务器,并多线程验证代理服务器ps 代理服务器是从http://www.cnproxy.com/ (测试只选择了8个页面)抓取2. 抓取一个网站的图片地址,多线程随机取一个代理服务器下载图片二、实现代码

代码如下:

#!/usr/bin/env python#coding:utf-8

import urllib2import reimport threadingimport timeimport random

rawproxylist = []checkedproxylist = []imgurl_list = []

#抓取代理网站portdicts ={‘v’:”3″,’m’:”4″,’a’:”2″,’l’:”9″,’q’:”0″,’b’:”5″,’i’:”7″,’w’:”6″,’r’:”8″,’c’:”1″}targets = []for i in xrange(1,9): target = r”http://www.cnproxy.com/proxy%d.html” % i targets.append(target)#print targets

#抓取代理服务器正则p = re.compile(r”'(.+?)document.write\(“:”\+(.+?)\)《script》(.+?).+?(.+?)”’)

#获取代理的类class proxyget(threading.thread): def __init__(self,target): threading.thread.__init__(self) self.target = target

def getproxy(self): print “代理服务器目标网站: ” + self.target req = urllib2.urlopen(self.target) result = req.read() #print chardet.detect(result) matchs = p.findall(result) for row in matchs: ip=row[0] port =row[1] port = map(lambda x:portdicts[x],port.split(‘+’)) port = ”.join(port) agent = row[2] addr = row[3].decode(“cp936”).encode(“utf-8”) proxy = [ip,port,addr] #print proxy rawproxylist.append(proxy)

def run(self): self.getproxy()

#检验代理的类class proxycheck(threading.thread): def __init__(self,proxylist): threading.thread.__init__(self) self.proxylist = proxylist self.timeout = 5 self.testurl = “http://www.baidu.com/” self.teststr = “030173”

def checkproxy(self): cookies = urllib2.httpcookieprocessor() for proxy in self.proxylist: proxyhandler = urllib2.proxyhandler({“http” : r’http://%s:%s’ %(proxy[0],proxy[1])}) #print r’http://%s:%s’ %(proxy[0],proxy[1]) opener = urllib2.build_opener(cookies,proxyhandler) opener.addheaders = [(‘user-agent’, ‘mozilla/5.0 (windows nt 6.2; wow64; rv:22.0) gecko/20100101 firefox/22.0’)] #urllib2.install_opener(opener) t1 = time.time()

try: #req = urllib2.urlopen(“http://www.baidu.com”, timeout=self.timeout) req = opener.open(self.testurl, timeout=self.timeout) #print “urlopen is ok….” result = req.read() #print “read html….” timeused = time.time() – t1 pos = result.find(self.teststr) #print “pos is %s” %pos

if pos > 1: checkedproxylist.append((proxy[0],proxy[1],proxy[2],timeused)) #print “ok ip: %s %s %s %s” %(proxy[0],proxy[1],proxy[2],timeused) else: continue except exception,e: #print e.message continue

def run(self): self.checkproxy()

#获取图片地址函数def imgurllist(url_home): global imgurl_list home_page = urllib2.urlopen(url_home) url_re = re.compile(r”) pic_re = re.compile(r’