嘗試使用Python多線程抓取代理服務(wù)器IP地址的示例
更新時(shí)間:2015年11月09日 15:09:47 投稿:goldensun
這篇文章主要介紹了嘗試使用Python多線程抓取代理服務(wù)器IP地址的示例,盡管有GIL的存在使得Python并不能真正實(shí)現(xiàn)多線程并行,需要的朋友可以參考下
這里以抓取 http://www.proxy.com.ru 站點(diǎn)的代理服務(wù)器為例,代碼如下:
#!/usr/bin/env python
#coding:utf-8
import urllib2
import re
import threading
import time
import MySQLdb
rawProxyList = []
checkedProxyList = []
#抓取代理網(wǎng)站
targets = []
for i in xrange(1,42):
target = r"http://www.proxy.com.ru/list_%d.html" % i
targets.append(target)
#抓取代理服務(wù)器正則
p = re.compile(r'''<tr><b><td>(\d+)</td><td>(.+?)</td><td>(\d+)</td><td>(.+?)</td><td>(.+?)</td></b></tr>''')
#獲取代理的類
class ProxyGet(threading.Thread):
def __init__(self,target):
threading.Thread.__init__(self)
self.target = target
def getProxy(self):
print "代理服務(wù)器目標(biāo)網(wǎng)站: " + self.target
req = urllib2.urlopen(self.target)
result = req.read()
#print chardet.detect(result)
matchs = p.findall(result)
# print matchs
for row in matchs:
ip=row[1]
port =row[2]
addr = row[4].decode("cp936").encode("utf-8")
proxy = [ip,port,addr]
print proxy
rawProxyList.append(proxy)
def run(self):
self.getProxy()
#檢驗(yàn)代理的類
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()
if __name__ == "__main__":
getThreads = []
checkThreads = []
#對每個(gè)目標(biāo)網(wǎng)站開啟一個(gè)線程負(fù)責(zé)抓取代理
for i in range(len(targets)):
t = ProxyGet(targets[i])
getThreads.append(t)
for i in range(len(getThreads)):
getThreads[i].start()
for i in range(len(getThreads)):
getThreads[i].join()
print '.'*10+"總共抓取了%s個(gè)代理" %len(rawProxyList) +'.'*10
#開啟20個(gè)線程負(fù)責(zé)校驗(yàn),將抓取到的代理分成20份,每個(gè)線程校驗(yàn)一份
for i in range(20):
t = ProxyCheck(rawProxyList[((len(rawProxyList)+19)/20) * i:((len(rawProxyList)+19)/20) * (i+1)])
checkThreads.append(t)
for i in range(len(checkThreads)):
checkThreads[i].start()
for i in range(len(checkThreads)):
checkThreads[i].join()
print '.'*10+"總共有%s個(gè)代理通過校驗(yàn)" %len(checkedProxyList) +'.'*10
#插入數(shù)據(jù)庫,表結(jié)構(gòu)自己創(chuàng)建,四個(gè)字段ip,port,speed,address
def db_insert(insert_list):
try:
conn = MySQLdb.connect(host="localhost", user="root", passwd="admin",db="m_common",charset='utf8')
cursor = conn.cursor()
cursor.execute('delete from proxy')
cursor.execute('alter table proxy AUTO_INCREMENT=1')
cursor.executemany("INSERT INTO proxy(ip,port,speed,address) VALUES (%s,%s,%s,%s)",insert_list)
conn.commit()
cursor.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
#代理排序持久化
proxy_ok = []
f= open("proxy_list.txt",'w+')
for proxy in sorted(checkedProxyList,cmp=lambda x,y:cmp(x[3],y[3])):
if proxy[3] < 8:
#print "checked proxy is: %s:%s\t%s\t%s" %(proxy[0],proxy[1],proxy[2],proxy[3])
proxy_ok.append((proxy[0],proxy[1],proxy[3],proxy[2]))
f.write("%s:%s\t%s\t%s\n"%(proxy[0],proxy[1],proxy[2],proxy[3]))
f.close()
db_insert(proxy_ok)
測試:
python proxy.py
結(jié)果如下:
['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'] ['200.84.116.99', '9064', '\xe5\xa7\x94\xe5\x86\x85\xe7\x91\x9e\xe6\x8b\x89 '] ['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'] ..........總共抓取了1921個(gè)代理.......... ..........總共有524個(gè)代理通過校驗(yàn).......... # more proxy_list.txt 202.106.169.142:80 北京市 聯(lián)通ADSL 0.291432857513 111.13.136.59:80 北京市 移動 0.297957897186 111.13.136.56:80 北京市 移動 0.373070955276 111.206.81.248:80 北京市 聯(lián)通 0.403017997742 111.13.136.58:80 北京市 移動 0.414332151413 124.202.217.134:8118 北京市 電信通 0.416817903519 124.202.183.218:8118 北京市 電信通 0.426618099213 120.132.71.232:80 北京市 聯(lián)通 0.440200090408 61.232.6.164:8081 北京市 鐵通 0.469615936279 118.144.96.253:80 北京市 電信通 0.485229969025 203.192.10.66:80 北京市 新華社 0.51485991478 124.202.182.22:8118 北京市 電信通 0.553130865097
數(shù)據(jù)庫:
mysql> select * from m_common.proxy limit 10;
+----------+-----------------+------+----------+----------------------+---------------------+ | proxy_id | ip | port | speed | address | create_time | +----------+-----------------+------+----------+----------------------+---------------------+ | 1 | 202.106.169.142 | 80 | 0.291433 | 北京市 聯(lián)通ADSL | 2015-02-26 11:29:24 | | 2 | 111.13.136.59 | 80 | 0.297958 | 北京市 移動 | 2015-02-26 11:29:24 | | 3 | 111.13.136.56 | 80 | 0.373071 | 北京市 移動 | 2015-02-26 11:29:24 | | 4 | 111.206.81.248 | 80 | 0.403018 | 北京市 聯(lián)通 | 2015-02-26 11:29:24 | | 5 | 111.13.136.58 | 80 | 0.414332 | 北京市 移動 | 2015-02-26 11:29:24 | | 6 | 124.202.217.134 | 8118 | 0.416818 | 北京市 電信通 | 2015-02-26 11:29:24 | | 7 | 124.202.183.218 | 8118 | 0.426618 | 北京市 電信通 | 2015-02-26 11:29:24 | | 8 | 120.132.71.232 | 80 | 0.4402 | 北京市 聯(lián)通 | 2015-02-26 11:29:24 | | 9 | 61.232.6.164 | 8081 | 0.469616 | 北京市 鐵通 | 2015-02-26 11:29:24 | | 10 | 118.144.96.253 | 80 | 0.48523 | 北京市 電信通 | 2015-02-26 11:29:24 | +----------+-----------------+------+----------+----------------------+---------------------+ 10 rows in set (0.00 sec)
您可能感興趣的文章:
- Python使用django獲取用戶IP地址的方法
- Python實(shí)現(xiàn)通過解析域名獲取ip地址的方法分析
- Python3獲取電腦IP、主機(jī)名、Mac地址的方法示例
- python獲取本機(jī)所有IP地址的方法
- Python簡單獲取網(wǎng)卡名稱及其IP地址的方法【基于psutil模塊】
- 詳解Python判定IP地址合法性的三種方法
- Python獲取本機(jī)所有網(wǎng)卡ip,掩碼和廣播地址實(shí)例代碼
- Python查詢IP地址歸屬完整代碼
- Python2.7基于淘寶接口獲取IP地址所在地理位置的方法【測試可用】
- Python django框架應(yīng)用中實(shí)現(xiàn)獲取訪問者ip地址示例
相關(guān)文章
Python腳本開發(fā)中的命令行參數(shù)及傳參示例詳解
這篇文章主要為大家介紹了Python腳本開發(fā)中的命令行參數(shù)及傳參示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
python 圖像增強(qiáng)算法實(shí)現(xiàn)詳解
這篇文章主要介紹了python 圖像增強(qiáng)算法實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Python實(shí)現(xiàn)小黑屋游戲的完整實(shí)例
這篇文章主要給大家介紹了關(guān)于Python實(shí)現(xiàn)小黑屋游戲的完整實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Pytorch?nn.Unfold()?與?nn.Fold()圖碼詳解(最新推薦)
這篇文章主要介紹了Pytorch?nn.Unfold()?與?nn.Fold()圖碼詳解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-05-05
Python通過requests模塊實(shí)現(xiàn)抓取王者榮耀全套皮膚
只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不如實(shí)踐帶來的提升快,只有在實(shí)例中才能獲得能力的提升,本篇文章手把手帶你用Python實(shí)現(xiàn)抓取王者榮耀全套皮膚,大家可以在過程中查缺補(bǔ)漏,提升水平2021-10-10
Python實(shí)現(xiàn)圖片指定位置加圖片水印(附Pyinstaller打包exe)
這篇文章主要介紹了Python實(shí)現(xiàn)圖片指定位置加圖片水印,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03

