Python多线程抓取代理服务器
这里以抓取 http://www.proxy.com.ru 站点的代理服务器为例,代码如下:
1#!/usr/bin/env python
2#coding:utf-8
3import urllib2
4import re
5import threading
6import time
7import MySQLdb
8rawProxyList = []
9checkedProxyList = []
10#抓取代理网站
11targets = []
12for i in xrange(1,42):
13 target = r"http://www.proxy.com.ru/list_%d.html" % i
14 targets.append(target)
15#抓取代理服务器正则
16p = re.compile(r'''<tr><b><td>(\d+)</td><td>(.+?)</td><td>(\d+)</td><td>(.+?)</td><td>(.+?)</td></b></tr>''')
17#获取代理的类
18class ProxyGet(threading.Thread):
19 def __init__(self,target):
20 threading.Thread.__init__(self)
21 self.target = target
22 def getProxy(self):
23 print "代理服务器目标网站: " + self.target
24 req = urllib2.urlopen(self.target)
25 result = req.read()
26 #print chardet.detect(result)
27 matchs = p.findall(result)
28# print matchs
29 for row in matchs:
30 ip=row[1]
31 port =row[2]
32 addr = row[4].decode("cp936").encode("utf-8")
33 proxy = [ip,port,addr]
34 print proxy
35 rawProxyList.append(proxy)
36 def run(self):
37 self.getProxy()
38#检验代理的类
39class ProxyCheck(threading.Thread):
40 def __init__(self,proxyList):
41 threading.Thread.__init__(self)
42 self.proxyList = proxyList
43 self.timeout = 5
44 self.testUrl = "http://www.baidu.com/"
45 self.testStr = "030173"
46 def checkProxy(self):
47 cookies = urllib2.HTTPCookieProcessor()
48 for proxy in self.proxyList:
49 proxyHandler = urllib2.ProxyHandler({"http" : r'http://%s:%s' %(proxy[0],proxy[1])})
50 #print r'http://%s:%s' %(proxy[0],proxy[1])
51 opener = urllib2.build_opener(cookies,proxyHandler)
52 opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0')]
53 #urllib2.install_opener(opener)
54 t1 = time.time()
55 try:
56 #req = urllib2.urlopen("http://www.baidu.com", timeout=self.timeout)
57 req = opener.open(self.testUrl, timeout=self.timeout)
58 #print "urlopen is ok...."
59 result = req.read()
60 #print "read html...."
61 timeused = time.time() - t1
62 pos = result.find(self.testStr)
63 #print "pos is %s" %pos
64 if pos > 1:
65 checkedProxyList.append((proxy[0],proxy[1],proxy[2],timeused))
66 #print "ok ip: %s %s %s %s" %(proxy[0],proxy[1],proxy[2],timeused)
67 else:
68 continue
69 except Exception,e:
70 #print e.message
71 continue
72 def run(self):
73 self.checkProxy()
74if __name__ == "__main__":
75 getThreads = []
76 checkThreads = []
77#对每个目标网站开启一个线程负责抓取代理
78for i in range(len(targets)):
79 t = ProxyGet(targets[i])
80 getThreads.append(t)
81for i in range(len(getThreads)):
82 getThreads[i].start()
83for i in range(len(getThreads)):
84 getThreads[i].join()
85print '.'*10+"总共抓取了%s个代理" %len(rawProxyList) +'.'*10
86#开启20个线程负责校验,将抓取到的代理分成20份,每个线程校验一份
87for i in range(20):
88 t = ProxyCheck(rawProxyList[((len(rawProxyList)+19)/20) * i:((len(rawProxyList)+19)/20) * (i+1)])
89 checkThreads.append(t)
90for i in range(len(checkThreads)):
91 checkThreads[i].start()
92for i in range(len(checkThreads)):
93 checkThreads[i].join()
94print '.'*10+"总共有%s个代理通过校验" %len(checkedProxyList) +'.'*10
95#插入数据库,表结构自己创建,四个字段ip,port,speed,address
96def db_insert(insert_list):
97 try:
98 conn = MySQLdb.connect(host="localhost", user="root", passwd="admin",db="m_common",charset='utf8')
99 cursor = conn.cursor()
100 cursor.execute('delete from proxy')
101 cursor.execute('alter table proxy AUTO_INCREMENT=1')
102 cursor.executemany("INSERT INTO proxy(ip,port,speed,address) VALUES (%s,%s,%s,%s)",insert_list)
103 conn.commit()
104 cursor.close()
105 conn.close()
106 except MySQLdb.Error,e:
107 print "Mysql Error %d: %s" % (e.args[0], e.args[1])
108#代理排序持久化
109proxy_ok = []
110f= open("proxy_list.txt",'w+')
111for proxy in sorted(checkedProxyList,cmp=lambda x,y:cmp(x[3],y[3])):
112 if proxy[3] < 8:
113 #print "checked proxy is: %s:%s\t%s\t%s" %(proxy[0],proxy[1],proxy[2],proxy[3])
114 proxy_ok.append((proxy[0],proxy[1],proxy[3],proxy[2]))
115 f.write("%s:%s\t%s\t%s\n"%(proxy[0],proxy[1],proxy[2],proxy[3]))
116f.close()
117db_insert(proxy_ok)
测试: python proxy.py
结果如下:
1['61.58.94.179', '8088', '\xe5\x8f\xb0\xe6\xb9\xbe\xe7\x9c\x81 \xe5\x8f\xb0\xe6\xb9\xbe\xe5\xae\xbd\xe9\xa2\x91\xe9\x80\x9a\xe8\xae\xaf\xe9\xa1\xbe\xe9\x97\xae\xe8\x82\xa1\xe4\xbb\xbd\xe6\x9c\x89\xe9\x99\x90\xe5\x85\xac\xe5\x8f\xb8']
2['200.84.116.99', '9064', '\xe5\xa7\x94\xe5\x86\x85\xe7\x91\x9e\xe6\x8b\x89 ']
3['183.223.204.8', '8123', '\xe5\x9b\x9b\xe5\xb7\x9d\xe7\x9c\x81\xe8\x87\xaa\xe8\xb4\xa1\xe5\xb8\x82 \xe7\xa7\xbb\xe5\x8a\xa8']
4..........总共抓取了1921个代理..........
5..........总共有524个代理通过校验..........
6
7# more proxy_list.txt
8
9202.106.169.142:80 北京市 联通ADSL 0.291432857513
10111.13.136.59:80 北京市 移动 0.297957897186
11111.13.136.56:80 北京市 移动 0.373070955276
12111.206.81.248:80 北京市 联通 0.403017997742
13111.13.136.58:80 北京市 移动 0.414332151413
14124.202.217.134:8118 北京市 电信通 0.416817903519
15124.202.183.218:8118 北京市 电信通 0.426618099213
16120.132.71.232:80 北京市 联通 0.440200090408
1761.232.6.164:8081 北京市 铁通 0.469615936279
18118.144.96.253:80 北京市 电信通 0.485229969025
19203.192.10.66:80 北京市 新华社 0.51485991478
20124.202.182.22:8118 北京市 电信通 0.553130865097
数据库:
1mysql> select * from m_common.proxy limit 10;
2+----------+-----------------+------+----------+----------------------+---------------------+
3| proxy_id | ip | port | speed | address | create_time |
4+----------+-----------------+------+----------+----------------------+---------------------+
5| 1 | 202.106.169.142 | 80 | 0.291433 | 北京市 联通ADSL | 2015-02-26 11:29:24 |
6| 2 | 111.13.136.59 | 80 | 0.297958 | 北京市 移动 | 2015-02-26 11:29:24 |
7| 3 | 111.13.136.56 | 80 | 0.373071 | 北京市 移动 | 2015-02-26 11:29:24 |
8| 4 | 111.206.81.248 | 80 | 0.403018 | 北京市 联通 | 2015-02-26 11:29:24 |
9| 5 | 111.13.136.58 | 80 | 0.414332 | 北京市 移动 | 2015-02-26 11:29:24 |
10| 6 | 124.202.217.134 | 8118 | 0.416818 | 北京市 电信通 | 2015-02-26 11:29:24 |
11| 7 | 124.202.183.218 | 8118 | 0.426618 | 北京市 电信通 | 2015-02-26 11:29:24 |
12| 8 | 120.132.71.232 | 80 | 0.4402 | 北京市 联通 | 2015-02-26 11:29:24 |
13| 9 | 61.232.6.164 | 8081 | 0.469616 | 北京市 铁通 | 2015-02-26 11:29:24 |
14| 10 | 118.144.96.253 | 80 | 0.48523 | 北京市 电信通 | 2015-02-26 11:29:24 |
15+----------+-----------------+------+----------+----------------------+---------------------+
1610 rows in set (0.00 sec)
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/python-multithreading-crawl-proxy-server/4143.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.