怎么用python抓取百度贴吧内容-成都创新互联网站建设

关于创新互联

多方位宣传企业产品与服务 突出企业形象

公司简介 公司的服务 荣誉资质 新闻动态 联系我们

怎么用python抓取百度贴吧内容

本篇内容介绍了“怎么用python抓取百度贴吧内容”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

伊川网站建设公司创新互联,伊川网站设计制作,有大型网站制作公司丰富经验。已为伊川近1000家提供企业网站建设服务。企业网站搭建\外贸网站建设要多少钱,请找那个售后服务好的伊川做网站的公司定做!

# -*- coding: utf-8
import urllib2
import urllib
import re,os
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

class Tiebar:
    #初始化数据
    def __init__(self,base_url,see_lz):
        self.base_url = base_url
        self.see_lz = '?see_lz=' + see_lz
        self.page = 1
        self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
        self.headers = { 'User-Agent' : self.user_agent }
        self.tool = Tool()
        self.out_put_file = 'd:/python/test/out.txt'
    #获取页面内容的方法
    def get_cotent(self,page):
        try:
            url = self.base_url + self.see_lz + '&pn=' + str(page)
            request = urllib2.Request(url,headers=self.headers)
            response = urllib2.urlopen(request)
            act_url = response.geturl()
            print 'init url=',url,'act url=',act_url
            if url == act_url:
                content = response.read()
                return content
            else:
                return None
        except urllib2.URLError, e:
            if hasattr(e,"reason"):
                print u"连接贴吧页面失败,错误原因",e.reason
                return None
    #获取帖子主题
    def get_titile(self):
        content = self.get_cotent(1)
        pattern = re.compile('

(.*?)

')
        result = re.search(pattern,content)
        if result:
            return result.group(1).strip()
        else:
            return None
    #获取帖子的页数
    def get_page_num(self):
        content = self.get_cotent(1)
        pattern = re.compile('
  •             return None
            patt_content = re.compile('(.*?).*?'
                        + '
    '
                        + '(.*?)',re.S)
            msg = re.findall(patt_content,content)
            for item in msg:
                str = str + '\n作者-----' + item[0] + '\n' + '帖子内容-----' + item[1].strip() + '\n'
                str = self.tool.replace(str)
                # print u'作者',item[0],u'帖子内容:',item[1]
            return str
        #写文件
        def writeStr2File(self,out_put_file,str1,append = 'a'):
            # 去掉文件,保留路径。比如 'a/b/c/d.txt' 经过下面代码会变成 'a/b/c'
            subPath = out_put_file[:out_put_file.rfind('/')]
            # 如果给定的路径中,文件夹不存在,则创建
            if not os.path.exists(subPath):
                os.makedirs(subPath)
            # 打开文件并将 str 内容写入给定的文件
            with open(out_put_file, append) as f:
                f.write(str1.strip()+'\n')


        def start_crawl(self):
            page_num = self.get_page_num()
            if page_num == None:
                print "url已失效,请重试!"
                return
            print u"该帖子共有" + str(page_num) + u"页数据"
            for i in range(1,int(page_num)+1):
                print u"正在写入第" + str(i) + u"页数据..."
                content = "正在写入第" + str(i) + u"页数据------------------------------------\n" + self.get_tiebar(i)
                self.writeStr2File(self.out_put_file,content)


    class Tool:
        #去除img标签
        patt_img = re.compile(r'')
        patt_herf = re.compile(r'|')
        patt_br = re.compile(r'
    {1,3}')


        def replace(self,content):
            content = re.sub(self.patt_img,"",content)
            content = re.sub(self.patt_herf,"",content)
            content = re.sub(self.patt_br,"\n",content)
            return content.strip()

    tiebar = Tiebar('http://tieba.baidu.com/p/3138733512','1')
    # title = tiebar.get_titile()
    # page_num = tiebar.get_page_num()
    # print title,page_num
    tiebar.start_crawl()

    “怎么用python抓取百度贴吧内容”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


    文章标题:怎么用python抓取百度贴吧内容
    URL分享:http://kswsj.cn/article/jehgis.html