Python爬虫基础知识:百度贴吧网络爬虫及源码分享

糖豆贴心提醒,本文阅读时间6分钟

百度贴吧的爬虫制作和糗百的爬虫制作原理基本相同,都是通过查看源码扣出关键数据,然后将其存储到本地txt文件。

项目内容:

用Python写的百度贴吧的网络爬虫。

使用方法:

新建一个BugBaidu.py文件,然后将代码复制到里面后,双击运行。

程序功能:

将贴吧中楼主发布的内容打包txt存储到本地。

原理解释:

首先,先浏览一下某一条贴吧,点击只看楼主并点击第二页之后url发生了一点变化,变成了:

http://tieba.baidu.com/p/2296712428?see_lz=1&pn=1

可以看出来,see_lz=1是只看楼主,pn=1是对应的页码,记住这一点为以后的编写做准备。

这就是我们需要利用的url。

接下来就是查看页面源码。

首先把题目抠出来存储文件的时候会用到。

可以看到百度使用gbk编码,标题使用h1标记:

同样,正文部分用div和class综合标记,接下来要做的只是用正则表达式来匹配即可。

运行截图:

生成的txt文件:

以下为本次项目源码:

  1. # -*- coding: utf-8 -*-  
  2. #---------------------------------------  
  3. #   程序:百度贴吧爬虫  
  4. #   版本:0.5  
  5. #   作者:why  
  6. #   日期:2013-05-16  
  7. #   语言:Python 2.7  
  8. #   操作:输入网址后自动只看楼主并保存到本地文件  
  9. #   功能:将楼主发布的内容打包txt存储到本地。  
  10. #---------------------------------------  
  11.    
  12. import string  
  13. import urllib2  
  14. import re  
  15.   
  16. #----------- 处理页面上的各种标签 -----------  
  17. class HTML_Tool:  
  18.     # 用非 贪婪模式 匹配 t 或者 n 或者 空格 或者 超链接 或者 图片  
  19.     BgnCharToNoneRex = re.compile("(t|n| |<a.*?>|<img.*?>)")  
  20.       
  21.     # 用非 贪婪模式 匹配 任意<>标签  
  22.     EndCharToNoneRex = re.compile("<.*?>")  
  23.   
  24.     # 用非 贪婪模式 匹配 任意<p>标签  
  25.     BgnPartRex = re.compile("<p.*?>")  
  26.     CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)")  
  27.     CharToNextTabRex = re.compile("<td>")  
  28.   
  29.     # 将一些html的符号实体转变为原始符号  
  30.     replaceTab = [("<","<"),(">",">"),("&","&"),("&","""),(" "," ")]  
  31.       
  32.     def Replace_Char(self,x):  
  33.         x = self.BgnCharToNoneRex.sub("",x)  
  34.         x = self.BgnPartRex.sub("n    ",x)  
  35.         x = self.CharToNewLineRex.sub("n",x)  
  36.         x = self.CharToNextTabRex.sub("t",x)  
  37.         x = self.EndCharToNoneRex.sub("",x)  
  38.   
  39.         for t in self.replaceTab:    
  40.             x = x.replace(t[0],t[1])    
  41.         return x    
  42.       
  43. class Baidu_Spider:  
  44.     # 申明相关的属性  
  45.     def __init__(self,url):    
  46.         self.myUrl = url + '?see_lz=1'  
  47.         self.datas = []  
  48.         self.myTool = HTML_Tool()  
  49.         print u'已经启动百度贴吧爬虫,咔嚓咔嚓'  
  50.     
  51.     # 初始化加载页面并将其转码储存  
  52.     def baidu_tieba(self):  
  53.         # 读取页面的原始信息并将其从gbk转码  
  54.         myPage = urllib2.urlopen(self.myUrl).read().decode("gbk")  
  55.         # 计算楼主发布内容一共有多少页  
  56.         endPage = self.page_counter(myPage)  
  57.         # 获取该帖的标题  
  58.         title = self.find_title(myPage)  
  59.         print u'文章名称:' + title  
  60.         # 获取最终的数据  
  61.         self.save_data(self.myUrl,title,endPage)  
  62.   
  63.     #用来计算一共有多少页  
  64.     def page_counter(self,myPage):  
  65.         # 匹配 "共有<span class="red">12</span>页" 来获取一共有多少页  
  66.         myMatch = re.search(r'class="red">(d+?)</span>', myPage, re.S)  
  67.         if myMatch:    
  68.             endPage = int(myMatch.group(1))  
  69.             print u'爬虫报告:发现楼主共有%d页的原创内容' % endPage  
  70.         else:  
  71.             endPage = 0  
  72.             print u'爬虫报告:无法计算楼主发布内容有多少页!'  
  73.         return endPage  
  74.   
  75.     # 用来寻找该帖的标题  
  76.     def find_title(self,myPage):  
  77.         # 匹配 <h1 class="core_title_txt" title="">xxxxxxxxxx</h1> 找出标题  
  78.         myMatch = re.search(r'<h1.*?>(.*?)</h1>', myPage, re.S)  
  79.         title = u'暂无标题'  
  80.         if myMatch:  
  81.             title  = myMatch.group(1)  
  82.         else:  
  83.             print u'爬虫报告:无法加载文章标题!'  
  84.         # 文件名不能包含以下字符:  / : * ? " < > |  
  85.         title = title.replace('\','').replace('/','').replace(':','').replace('*','').replace('?','').replace('"','').replace('>','').replace('<','').replace('|','')  
  86.         return title  
  87.   
  88.   
  89.     # 用来存储楼主发布的内容  
  90.     def save_data(self,url,title,endPage):  
  91.         # 加载页面数据到数组中  
  92.         self.get_data(url,endPage)  
  93.         # 打开本地文件  
  94.         f = open(title+'.txt','w+')  
  95.         f.writelines(self.datas)  
  96.         f.close()  
  97.         print u'爬虫报告:文件已下载到本地并打包成txt文件'  
  98.         print u'请按任意键退出...'  
  99.         raw_input();  
  100.   
  101.     # 获取页面源码并将其存储到数组中  
  102.     def get_data(self,url,endPage):  
  103.         url = url + '&pn='  
  104.         for i in range(1,endPage+1):  
  105.             print u'爬虫报告:爬虫%d号正在加载中...' % i  
  106.             myPage = urllib2.urlopen(url + str(i)).read()  
  107.             # 将myPage中的html代码处理并存储到datas里面  
  108.             self.deal_data(myPage.decode('gbk'))  
  109.               
  110.   
  111.     # 将内容从页面代码中抠出来  
  112.     def deal_data(self,myPage):  
  113.         myItems = re.findall('id="post_content.*?>(.*?)</div>',myPage,re.S)  
  114.         for item in myItems:  
  115.             data = self.myTool.Replace_Char(item.replace("n","").encode('gbk'))  
  116.             self.datas.append(data+'n')  
  117.   
  118.   
  119.   
  120. #-------- 程序入口处 ------------------  
  121. print u"""#--------------------------------------- 
  122. #   程序:百度贴吧爬虫 
  123. #   版本:0.5 
  124. #   作者:why 
  125. #   日期:2013-05-16 
  126. #   语言:Python 2.7 
  127. #   操作:输入网址后自动只看楼主并保存到本地文件 
  128. #   功能:将楼主发布的内容打包txt存储到本地。 
  129. #--------------------------------------- 
  130. """  
  131.   
  132. # 以某小说贴吧为例子  
  133. # bdurl = 'http://tieba.baidu.com/p/2296712428?see_lz=1&pn=1'  
  134.   
  135. print u'请输入贴吧的地址最后的数字串:'  
  136. bdurl = 'http://tieba.baidu.com/p/' + str(raw_input(u'http://tieba.baidu.com/p/'))   
  137.   
  138. #调用  
  139. mySpider = Baidu_Spider(bdurl)  
  140. mySpider.baidu_tieba()  

登入/注册
卧槽~你还有脸回来
没有账号? 忘记密码?