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

代码缘起

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

代码思路

  1. 用一个文本文件记录需要验证的站点,其中数据格式如下
    站点名称|站点地址|错误次数
    一共三个字段,每个字段用”|”进行分割,其中错误次数是指该站点累计出错的次数(目前主要通过http状态的非200确定。
  2. 通过队列开多线程,加速验证过程。
  • 所有输入数据读入一个queue中,所有输出数据到一个queue中。
  • 建立线程函数,在线程函数中通过queue.get(False)获得相关数据,设置False表示不等待,这样才不会出错。
  • 在主程序中启动线程
  • 在主程序中监控线程运行情况,并回收数据,写入文件

代码自己会说话

#coding=utf-8
#验证站点的活动性,标注死站点
#使用多线程模式
import time
import os
import re
import sys
import requests
import threading
import Queue

def 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=5
for 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
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞