分享

python 爬虫基础(1)

 free_light 2014-05-01

001# -*- coding: utf-8 -*-
002#---------------------------------------
003#   程序:百度贴吧爬虫
004#   版本:0.5
005#   作者:why
006#   日期:2013-05-16
007#   语言:Python 2.7
008#   操作:输入网址后自动只看楼主并保存到本地文件
009#   功能:将楼主发布的内容打包txt存储到本地。
010#---------------------------------------
011  
012import string
013import urllib2
014import re
015 
016#----------- 处理页面上的各种标签 -----------
017class 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 = [("<","<"),(">",">"),("&","&"),("&","\""),(" "," ")]
031     
032    def Replace_Char(self,x):
033        x = self.BgnCharToNoneRex.sub("",x)
034        x = self.BgnPartRex.sub("\n    ",x)
035        x = self.CharToNewLineRex.sub("\n",x)
036        x = self.CharToNextTabRex.sub("\t",x)
037        x = self.EndCharToNoneRex.sub("",x)
038 
039        for t in self.replaceTab: 
040            x = x.replace(t[0],t[1]) 
041        return
042     
043class 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        f = 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 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#-------- 程序入口处 ------------------
121print 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 
135print u'请输入贴吧的地址最后的数字串:'
136bdurl = 'http://tieba.baidu.com/p/' + str(raw_input(u'http://tieba.baidu.com/p/'))
137 
138#调用
139mySpider = Baidu_Spider(bdurl)
140mySpider.baidu_tieba()

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多