为了账号安全,请及时绑定邮箱和手机立即绑定

python多线程验证web站点活性代码

标签:
Java Python

代码缘起

在日常的网页挖掘中,有些站点的数据需要经常性的进行爬取,但是有时候会出现部分web站点因为种种原因而下线,这时爬取将严重影响数据爬取效率,通过编写一个web站点状态的验证,在网站爬取前,首先明确站点状态,并记录状态,从而对于每个站点的出错概率和当前状态有所了解,避免盲目爬取

代码思路

  1. 用一个文本文件记录需要验证的站点,其中数据格式如下
    站点名称|站点地址|错误次数
    一共三个字段,每个字段用"|"进行分割,其中错误次数是指该站点累计出错的次数(目前主要通过http状态的非200确定。

  2. 通过队列开多线程,加速验证过程。

  • 所有输入数据读入一个queue中,所有输出数据到一个queue中。

  • 建立线程函数,在线程函数中通过queue.get(False)获得相关数据,设置False表示不等待,这样才不会出错。

  • 在主程序中启动线程

  • 在主程序中监控线程运行情况,并回收数据,写入文件

代码自己会说话

#coding=utf-8#验证站点的活动性,标注死站点#使用多线程模式import timeimport osimport reimport sysimport requestsimport threadingimport Queuedef myinit():
    reload(sys)
    sys.setdefaultencoding('utf8')##检查站点活动函数def chect_active(url,chaoshi=10):
    code=0
    try:
        r=requests.get(url,timeout=chaoshi)
        code=r.status_code    except Exception , e:
        code=-1
    if code!=200:
        code=-1
    return code#检查线程函数def thread_check_active(jobslink_queue,jieguo_queue):
    while True:        try:
            dic_webinfo=jobslink_queue.get(False)  #False =Don't wait
        except Queue.Empty:            return
        if chect_active(dic_webinfo['weburl'])==-1:
            dic_webinfo['count']=int(dic_webinfo['count'])+1
        jieguo_queue.put(dic_webinfo)

myinit()

jobslink=Queue.Queue(0)
jieguo=Queue.Queue(0)

xiaoshuo_zhandian="xiao_shuo_zhan_dian.txt"inputfile = open(xiaoshuo_zhandian, 'r')
list_of_all_the_lines = inputfile.readlines( )
inputfile.close()for line in list_of_all_the_lines:
    (t2,xiaoshuourl,count)=line.decode('utf8').rstrip().split("|")
    jobslink.put({'webname':t2,'weburl':xiaoshuourl,'count':count})

THREAD_NUM=5for x in range(THREAD_NUM):
        t=threading.Thread(target=thread_check_active,args=(jobslink,jieguo))
        t.start()

f=open(xiaoshuo_zhandian,'w')
mycount=0#结果数据写入文件while (threading.activeCount()>1) or (not jobslink.empty()):        while jieguo.qsize()>0 :            if(jieguo.qsize()>0):
                jieguotxt=jieguo.get()
                f.write("%s|%s|%d\n"%(jieguotxt['webname'],jieguotxt['weburl'],int(jieguotxt['count'])))
        mycount=mycount+1
        if(mycount%100)==0:            print u"%d:  活动线程:%d,剩余连接数:%d,结果剩余条数:%d"%(mycount,threading.activeCount(),jobslink.qsize(),jieguo.qsize())
        time.sleep(0.01)
f.close()print u"站点验证完成"



作者:明慢慢
链接:https://www.jianshu.com/p/9c54fc346147


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消