多线程获取腾讯新闻,多线程获取腾讯,# -*- coding


# -*- coding: utf-8 -*-import urllib2import reimport osimport threadingimport Queue# 配置信息pageStart   = 1pageEnd     = 3000root = "E:\\\\qq.com\\\\news\\\\d\\\\20130104\\\\"# 正则def filter_tags(htmlstr):    re_cdata=re.compile('//<!\\[CDATA\\[[^>]*//\\]\\]>',re.I) #匹配CDATA    re_script=re.compile('<\\s*script[^>]*>[^<]*<\\s*/\\s*script\\s*>',re.I)#Script    re_style=re.compile('<\\s*style[^>]*>[^<]*<\\s*/\\s*style\\s*>',re.I)#style    re_p=re.compile('<P\\s*?/?>')#处理换行    re_h=re.compile('</?\\w+[^>]*>')#HTML标签    re_comment=re.compile('<!--[^>]*-->')#HTML注释    s=re_cdata.sub('',htmlstr)#去掉CDATA    s=re_script.sub('',s) #去掉SCRIPT    s=re_style.sub('',s)#去掉style    s=re_p.sub('\\r\\n',s)#将<p>转换为换行    s=re_h.sub('',s) #去掉HTML 标签    s=re_comment.sub('',s)#去掉HTML注释      blank_line=re.compile('\\n+')#去掉多余的空行    s=blank_line.sub('\\n',s)    return snQueue = Queue.Queue()class DownloadPage(threading.Thread):    def __init__ (self, nQueue):        threading.Thread.__init__(self)        self.nQueue = nQueue    def run (self):        while True:            page = self.nQueue.get()            url = "http://news.qq.com/a/20130104/"+page+".htm"            try:#异常跳出                sub_web = urllib2.urlopen(url).read()#打开完整url链接,获取内容            except:                print page+' Failed'                continue            re_keyt = "<h1>.+</h1>"#获取标题,此处的标题不含腾讯新闻的后缀比较方便            title = re.findall(re_keyt,sub_web)#去掉标题左右的html标签            re_keyc = re.compile("<div id=\\"Cnt-Main-Article-QQ\\".*</div>")#匹配正文内容的正则(个别页面无法获得,见if块)            content = re_keyc.findall(sub_web)#获得正文内容            if len(title)==0 or len(content)==0:                continue            re_content = filter_tags(title[0]+"\\r\\n"+content[0])#将标题和正文放到一起并去除html标签代码            # 目标路径            path = root+page+".txt"            # 收工            if os.path.isfile(path):                print 'file exists, go next.'                continue            else:                w=file(path,'w')#根据页面的文件名建立txt文件,并打开为写入方式                w.write(re_content)#写入获得的去除了html标签代码的标题和正文                w.close()#关闭文件        self.nQueue.task_done()def main ():    for i in range(pageStart, pageEnd):        page = str(i).zfill(6)        nQueue.put(page)    for i in range(5) :        tt = DownloadPage(nQueue)        tt.setDaemon(True)        tt.start()    nQueue.join()main()exit()#该片段来自于http://byrx.net

评论关闭