使用urllib2从百度帖吧获取楼主的所有发言

1. [代码][Python]代码     

001 # -*- coding: utf-8 -*-
002 #---------------------------------------
003 #   程序:百度贴吧爬虫
004 #   版本:0.5
005 #   作者:why
006 #   日期:2013-05-16
007 #   语言:Python 2.7
008 #   操作:输入网址后自动只看楼主并保存到本地文件
009 #   功能:将楼主发布的内容打包txt存储到本地。
010 #---------------------------------------
011   
012 import string
013 import urllib2
014 import re
015  
016 #----------- 处理页面上的各种标签 -----------
017 class HTML_Tool:
018     # 用非 贪婪模式 匹配 \t 或者 \n 或者 空格 或者 超链接 或者 图片
019     BgnCharToNoneRex = re.compile("(\t|\n| |<a.*?>|<img.*?>)")
020      
021     # 用非 贪婪模式 匹配 任意<>标签
022     EndCharToNoneRex = re.compile("<.*?>")
023  
024     # 用非 贪婪模式 匹配 任意<p>标签
025     BgnPartRex = re.compile("<p.*?>")
026     CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)")
027     CharToNextTabRex = re.compile("<td>")
028  
029     # 将一些html的符号实体转变为原始符号
030     replaceTab = [("&lt;","<"),("&gt;",">"),("&amp;","&"),("&amp;","\""),("&nbsp;"," ")]
031      
032     def Replace_Char(self,x):
033         = self.BgnCharToNoneRex.sub("",x)
034         = self.BgnPartRex.sub("\n    ",x)
035         = self.CharToNewLineRex.sub("\n",x)
036         = self.CharToNextTabRex.sub("\t",x)
037         = self.EndCharToNoneRex.sub("",x)
038  
039         for in self.replaceTab: 
040             = x.replace(t[0],t[1]) 
041         return 
042      
043 class Baidu_Spider:
044     # 申明相关的属性
045     def __init__(self,url): 
046         self.myUrl = url + '?see_lz=1'
047         self.datas = []
048         self.myTool = HTML_Tool()
049         print u'已经启动百度贴吧爬虫,咔嚓咔嚓'
050    
051     # 初始化加载页面并将其转码储存
052     def baidu_tieba(self):
053         # 读取页面的原始信息并将其从gbk转码
054         myPage = urllib2.urlopen(self.myUrl).read().decode("gbk")
055         # 计算楼主发布内容一共有多少页
056         endPage = self.page_counter(myPage)
057         # 获取该帖的标题
058         title = self.find_title(myPage)
059         print u'文章名称:' + title
060         # 获取最终的数据
061         self.save_data(self.myUrl,title,endPage)
062  
063     #用来计算一共有多少页
064     def page_counter(self,myPage):
065         # 匹配 "共有<span class="red">12</span>页" 来获取一共有多少页
066         myMatch = re.search(r'class="red">(\d+?)</span>', myPage, re.S)
067         if myMatch: 
068             endPage = int(myMatch.group(1))
069             print u'爬虫报告:发现楼主共有%d页的原创内容' % endPage
070         else:
071             endPage = 0
072             print u'爬虫报告:无法计算楼主发布内容有多少页!'
073         return endPage
074  
075     # 用来寻找该帖的标题
076     def find_title(self,myPage):
077         # 匹配 <h1 class="core_title_txt" title="">xxxxxxxxxx</h1> 找出标题
078         myMatch = re.search(r'<h1.*?>(.*?)</h1>', myPage, re.S)
079         title = u'暂无标题'
080         if myMatch:
081             title  = myMatch.group(1)
082         else:
083             print u'爬虫报告:无法加载文章标题!'
084         # 文件名不能包含以下字符: \ / : * ? " < > |
085         title =title.replace('\\','').replace('/','').replace(':','').replace('*','').replace('?','').replace('"','').replace('>','').replace('<','').replace('|','')
086         return title
087  
088  
089     # 用来存储楼主发布的内容
090     def save_data(self,url,title,endPage):
091         # 加载页面数据到数组中
092         self.get_data(url,endPage)
093         # 打开本地文件
094         = open(title+'.txt','w+')
095         f.writelines(self.datas)
096         f.close()
097         print u'爬虫报告:文件已下载到本地并打包成txt文件'
098         print u'请按任意键退出...'
099         raw_input();
100  
101     # 获取页面源码并将其存储到数组中
102     def get_data(self,url,endPage):
103         url = url + '&pn='
104         for 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()

2. [文件] 百度贴吧爬虫v0.5.py ~ 5KB     下载(5)     

001 # -*- coding: utf-8 -*-
002 #---------------------------------------
003 #   程序:百度贴吧爬虫
004 #   版本:0.5
005 #   作者:why
006 #   日期:2013-05-16
007 #   语言:Python 2.7
008 #   操作:输入网址后自动只看楼主并保存到本地文件
009 #   功能:将楼主发布的内容打包txt存储到本地。
010 #---------------------------------------
011   
012 import string
013 import urllib2
014 import re
015  
016 #----------- 处理页面上的各种标签 -----------
017 class HTML_Tool:
018     # 用非 贪婪模式 匹配 \t 或者 \n 或者 空格 或者 超链接 或者 图片
019     BgnCharToNoneRex = re.compile("(\t|\n| |<a.*?>|<img.*?>)")
020      
021     # 用非 贪婪模式 匹配 任意<>标签
022     EndCharToNoneRex = re.compile("<.*?>")
023  
024     # 用非 贪婪模式 匹配 任意<p>标签
025     BgnPartRex = re.compile("<p.*?>")
026     CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)")
027     CharToNextTabRex = re.compile("<td>")
028  
029     # 将一些html的符号实体转变为原始符号
030     replaceTab = [("&lt;","<"),("&gt;",">"),("&amp;","&"),("&amp;","\""),("&nbsp;"," ")]
031      
032     def Replace_Char(self,x):
033         = self.BgnCharToNoneRex.sub("",x)
034         = self.BgnPartRex.sub("\n    ",x)
035         = self.CharToNewLineRex.sub("\n",x)
036         = self.CharToNextTabRex.sub("\t",x)
037         = self.EndCharToNoneRex.sub("",x)
038  
039         for in self.replaceTab: 
040             = x.replace(t[0],t[1]) 
041         return 
042      
043 class Baidu_Spider:
044     # 申明相关的属性
045     def __init__(self,url): 
046         self.myUrl = url + '?see_lz=1'
047         self.datas = []
048         self.myTool = HTML_Tool()
049         print u'已经启动百度贴吧爬虫,咔嚓咔嚓'
050    
051     # 初始化加载页面并将其转码储存
052     def baidu_tieba(self):
053         # 读取页面的原始信息并将其从gbk转码
054         myPage = urllib2.urlopen(self.myUrl).read().decode("gbk")
055         # 计算楼主发布内容一共有多少页
056         endPage = self.page_counter(myPage)
057         # 获取该帖的标题
058         title = self.find_title(myPage)
059         print u'文章名称:' + title
060         # 获取最终的数据
061         self.save_data(self.myUrl,title,endPage)
062  
063     #用来计算一共有多少页
064     def page_counter(self,myPage):
065         # 匹配 "共有<span class="red">12</span>页" 来获取一共有多少页
066         myMatch = re.search(r'class="red">(\d+?)</span>', myPage, re.S)
067         if myMatch: 
068             endPage = int(myMatch.group(1))
069             print u'爬虫报告:发现楼主共有%d页的原创内容' % endPage
070         else:
071             endPage = 0
072             print u'爬虫报告:无法计算楼主发布内容有多少页!'
073         return endPage
074  
075     # 用来寻找该帖的标题
076     def find_title(self,myPage):
077         # 匹配 <h1 class="core_title_txt" title="">xxxxxxxxxx</h1> 找出标题
078         myMatch = re.search(r'<h1.*?>(.*?)</h1>', myPage, re.S)
079         title = u'暂无标题'
080         if myMatch:
081             title  = myMatch.group(1)
082         else:
083             print u'爬虫报告:无法加载文章标题!'
084         # 文件名不能包含以下字符: \ / : * ? " < > |
085         title =title.replace('\\','').replace('/','').replace(':','').replace('*','').replace('?','').replace('"','').replace('>','').replace('<','').replace('|','')
086         return title
087  
088  
089     # 用来存储楼主发布的内容
090     def save_data(self,url,title,endPage):
091         # 加载页面数据到数组中
092         self.get_data(url,endPage)
093         # 打开本地文件
094         = open(title+'.txt','w+')
095         f.writelines(self.datas)
096         f.close()
097         print u'爬虫报告:文件已下载到本地并打包成txt文件'
098         print u'请按任意键退出...'
099         raw_input();
100  
101     # 获取页面源码并将其存储到数组中
102     def get_data(self,url,endPage):
103         url = url + '&pn='
104         for 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()

3. [图片] QQ截图20130521131141.png    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Python中的`urllib`模块爬取百度贴吧网页内容涉及以下几个步骤: 1. 导入所需的库: ```python import urllib.request from bs4 import BeautifulSoup # 引入BeautifulSoup解析HTML ``` 2. 定义URL和请求头(模拟浏览器访问): ```python url = "https://tieba.baidu.com/" # 百度贴吧首页或其他具体页面地址 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' } # 设置用户代理,避免被识别为机器人 ``` 3. 发送GET请求并获取网页内容: ```python response = urllib.request.Request(url, headers=headers) with urllib.request.urlopen(response) as response_obj: html_content = response_obj.read().decode('utf-8') ``` 4. 解析网页内容: ```python soup = BeautifulSoup(html_content, 'lxml') # 使用BeautifulSoup解析HTML # 找到你需要的内容,如子列表、文章等,可能需要用到`soup.find_all()`或`.select()`方法 content_items = soup.select('.post-content') # 假设.post-content是子内容的CSS选择器 ``` 5. 处理数据: ```python for item in content_items: post_text = item.get_text() # 获取文本内容 print(post_text) ``` 6. 结果保存或进一步处理: ```python # 可选:将抓取的数据写入文件或数据库,或者做更复杂的分析操作 ``` 注意:在实际爬虫中,请遵守网站的robots.txt规则,并尊重版权,不要频繁发送请求导致服务器压力过大。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值