吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 10565|回复: 24
收起左侧

[Python 转载] 入门级Python网络爬虫

  [复制链接]
胡临任 发表于 2015-5-22 21:37
Python作为一门功能强大的脚本语言来说,经常被用来写爬虫程序,下面是Python爬虫多线程抓取代{过}{滤}理服务器

首先通过谷歌把包含代{过}{滤}理服务器地址的网页查出来,我选择从 http://www.88181.com/ 这个网站上去抓, 在它上面了爬了800个代{过}{滤}理(选择的8个页面)
#!/usr/bin/env python






#coding:utf-8


import urllib2
import re
import threading
import time

rawProxyList = []
checkedProxyList = []

#抓取代{过}{滤}理网站
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.88181.com/proxy%d.html" % i
        targets.append(target)
#print targets

#正则
p = re.compile(r'''<tr><td>(.+?)<SCRIPT type=text/javascript>document.write\(":"\+(.+?)\)</SCRIPT></td><td>(.+?)</td><td>.+?</td><td>(.+?)</td></tr>''')

#获取代{过}{滤}理的类
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()

if __name__ == "__main__":
    getThreads = []
    checkThreads = []

#对每个目标网站开启一个线程负责抓取代{过}{滤}理
for i in range(len(targets)):
    t = ProxyGet(targets)
    getThreads.append(t)

for i in range(len(getThreads)):
    getThreads.start()

for i in range(len(getThreads)):
    getThreads.join()

print '.'*10+"总共抓取了%s个代{过}{滤}理" %len(rawProxyList) +'.'*10

#开启20个线程负责校验,将抓取到的代{过}{滤}理分成20份,每个线程校验一份
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.start()

for i in range(len(checkThreads)):
    checkThreads.join()

print '.'*10+"总共有%s个代{过}{滤}理通过校验" %len(checkedProxyList) +'.'*10

#持久化
f= open("proxy_list.txt",'w+')
for proxy in sorted(checkedProxyList,cmp=lambda x,y:cmp(x[3],y[3])):
    print "checked proxy is: %s:%s\t%s\t%s" %(proxy[0],proxy[1],proxy[2],proxy[3])
    f.write("%s:%s\t%s\t%s\n"%(proxy[0],proxy[1],proxy[2],proxy[3]))
f.close()

部分log: 目标网站: http://www.88181.com/proxy1.html
目标网站: http://www.88181.com/proxy2.html
目标网站: http://www.88181.com/proxy3.html
目标网站: http://www.88181.com/proxy4.html
目标网站: http://www.88181.com/proxy5.html
目标网站: http://www.88181.com/proxy6.html
目标网站: http://www.88181.com/proxy7.html
目标网站: http://www.88181.com/proxy8.html
..........总共抓取了800个代{过}{滤}理..........
..........总共有478个代{过}{滤}理通过校验.........
173.213.113.111:8089    United States  0.341555833817
173.213.113.111:3128    United States  0.347477912903
210.101.131.232:8080    韩国 首尔      0.418715000153

免费评分

参与人数 2热心值 +2 收起 理由
小树丶 + 1 怎么用????
Lbf + 1 用心讨论,共获提升!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

wisology 发表于 2015-5-22 21:45
对python还不熟悉,支持一个。
一路有你 发表于 2015-5-22 21:51
头像被屏蔽
zhedielj 发表于 2015-5-22 22:37
caolcx 发表于 2015-5-24 17:23
这个爬虫的脚本感觉好厉害的样子啊,
tywolf 发表于 2015-5-25 10:59
这个爬虫脚本运行不起来的,list对象里不存在start
ipaddr 发表于 2015-9-10 15:37
学习一下
mrwinner 发表于 2015-11-18 10:49
为了爬虫学python ing
Lbf 发表于 2016-11-27 22:47
正在学习爬虫
蜗牛的春天 发表于 2016-11-29 10:03
谢谢楼主的分享
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-3-29 17:54

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表