Python+正则表达式编写多线程百度贴吧网页爬虫

来源:互联网 发布:java web面试题 编辑:程序博客网 时间:2024/05/18 08:31

其实本来是想做一个利用Python+XPath的贴吧爬虫,但是遇到了一些很奇怪的问题搞了一天也没有解决,所以只有用简单的正则表达式来代替XPath。
这个小爬虫是用于爬取一个帖子所有的回帖人+回帖内容+回帖时间,并导出到本地的文件中保存。本次测试的贴吧地址为:https://tieba.baidu.com/p/3905531791?pn中1-5页的所有内容。
利用多线程可以大大提高爬虫爬取速度,提高程序的效率。
因为百度贴吧的网页源码随时可能会改动,源码改动可能会导致正则表达式匹配不到正确的结果,所以这个爬虫具有一定的时效性。爬虫代码是根据最新的贴吧网页源码制作,若有变更,请读者自行修改。

# -*- coding:utf-8 -*-from multiprocessing.dummy import Pool as ThreadPoolimport requestsimport reimport sysreload(sys)sys.setdefaultencoding('utf-8')def write(content):  #将数据保存至本地文件中    f.writelines(u'回帖人:'+str(content['user_name'])+'\n')    f.writelines(u'回帖时间:'+str(content['reply_time'])+'\n')    f.writelines(u'回帖内容:'+unicode(content['content'])+'\n'+'\n')def spider_Re(url):    #利用正则表达式匹配提取网页信息    html = requests.get(url)    content_field = re.findall('<ul class="p_author">(.*?)<div class="j_lzl_container core_reply_wrapper',html.text,re.S)    item = {}    for each in content_field:        author = re.search('target="_blank">(.*?)</a>',each,re.S).group(1)        content = re.search('class="d_post_content j_d_post_content ">(.*?)</div><br>            </cc>',each,re.S).group(1).replace('<br>','\n')        reply_time = re.search('''[^/a>]</span><span class="tail-info">(.*?)</span></div>''',each,re.S).group(1)        print content        print author        print reply_time        item['user_name'] = author        item['content'] = content        item['reply_time'] = reply_time        write(item)if __name__ == '__main__':    pool = ThreadPool(4)   #参数取决于CPU的核心数    f = open('content.txt','w')    page=[]    for i in range(1,6):  #1到总页数+1        newpage = 'https://tieba.baidu.com/p/3905531791?pn=' + str(i)        page.append(newpage)    results = pool.map(spider_Re,page)    pool.close()    pool.join()    f.close()

这样基本就可以完成贴吧网页的爬取了。
如:

回帖人:jin70908469回帖内容:            游戏背景职业介绍巫师系列剧情讲解视频巫师前作故事梗概攻略心得,有些可能含有本作剧透,慎入!官方英文版攻略PDF 影响结局的选项纯堆DPS加点法印流加点三种流派的主要人物加点和培养<a href="http://jump2.bdimg.com/safecheck/index?url=x+Z5mMbGPAs95UolpNuq+CwM2BpViN6QF0BYrUCVRu8ACvHfW52JIJiw9jD7zZ68yExmB9N/65I="  target="_blank">http://tieba.baidu.com/p/3787258057</a>全地图技能点收集(魔力之所)<a href="http://jump2.bdimg.com/safecheck/index?url=x+Z5mMbGPAs95UolpNuq+CwM2BpViN6QF0BYrUCVRu9mNjDqZl39tlDLvtcpYTbcyExmB9N/65I="  target="_blank">http://tieba.baidu.com/p/3787534924</a>所有魔力之所,昆特牌玩家和销售卡牌的旅行者的位置<a href="http://jump2.bdimg.com/safecheck/index?url=x+Z5mMbGPAs95UolpNuq+CwM2BpViN6QF0BYrUCVRu9OnJoDv3V75Ppbi42L2g7XITkBmfiS/WpWpoifrx0i/9hNVf7JU91BgLHy2pejPhpWpoifrx0i/7Cj68W1k+ZNAG+4Cm4FSU0="  target="_blank">http://tieba.baidu.com/p/3790700051?pid=69022101270&amp;cid=0#69022101270</a>昆特牌全面解析<a href="http://jump2.bdimg.com/safecheck/index?url=x+Z5mMbGPAs95UolpNuq+CwM2BpViN6QF0BYrUCVRu8HXtSL9TnUr8YC6GYK0gQGyExmB9N/65I="  target="_blank">http://tieba.baidu.com/p/3806546863</a>所有昆特牌收集<a href="http://jump2.bdimg.com/safecheck/index?url=x+Z5mMbGPAs95UolpNuq+CwM2BpViN6QF0BYrUCVRu/f6TYTK+5+oR33i2kCddzcyExmB9N/65I="  target="_blank">http://tieba.baidu.com/p/3794649067</a>

仔细地看爬取出的文件信息就可以发现,回帖内容中会出现大量的类似于
<a href="......">http://.......</a><img .....>之类的标签内容,非常影响观感。
于是我尝试使用正则表达式清除这类标签信息,保留超链接标签中的文字。
添加下列代码:

    content = re.sub('''<a\shref=".*?>''', '', content, re.S).replace('</a>', '') #匹配删除<a href=""></a>标签    content = re.sub('''<img\sclass=".*?>''','',content,re.S)  #匹配删除<img>标签

这样大部分的标签就可以被删除:(有少部分还是删不掉不知道什么原因,请大神留言解答)

回帖人:jin70908469回帖时间:2015-07-19 17:48回帖内容:            游戏背景12代的游戏资源这里就不提供了,有意者可到相应贴吧或各大游戏网站自行寻找。不想玩前作或是没时间的吧友可阅读以下背景介绍。机核网制作的猎魔人系列背景介绍http://www.g-cores.com/witcher#charactor“猎魔人”系列的前世今生http://tieba.baidu.com/p/2167716421猎魔人的世界[小说剧透] http://tieba.baidu.com/p/3109151723狩魔猎人职业介绍http://tieba.baidu.com/p/3710504558巫师系列剧情讲解视频http://tieba.baidu.com/p/3693416865巫师前作故事梗概http://tieba.baidu.com/p/3736572554攻略心得,有些可能含有本作剧透,慎入!官方英文版攻略PDF http://pan.baidu.com/s/1jGgT706影响结局的选项http://tieba.baidu.com/p/3821337556纯堆DPS加点http://tieba.baidu.com/p/3784395921法印流加点http://tieba.baidu.com/p/3793006353三种流派的主要人物加点和培养http://tieba.baidu.com/p/3787258057全地图技能点收集(魔力之所)http://tieba.baidu.com/p/3787534924所有魔力之所,昆特牌玩家和销售卡牌的旅行者的位置http://tieba.baidu.com/p/3790700051?pid=69022101270&amp;cid=0#69022101270昆特牌全面解析http://tieba.baidu.com/p/3806546863所有昆特牌收集http://tieba.baidu.com/p/3794649067TW3在线官方地图 http://thewitcher.com/map

关于XPath版本的贴吧爬虫我会找机会再研究研究,成功后再发表分享。