溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么用python抓取百度貼吧內(nèi)容

發(fā)布時間:2022-01-18 14:30:06 來源:億速云 閱讀:155 作者:iii 欄目:編程語言

本篇內(nèi)容介紹了“怎么用python抓取百度貼吧內(nèi)容”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

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

class Tiebar:
    #初始化數(shù)據(jù)
    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'
    #獲取頁面內(nèi)容的方法
    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('<h4 .*?>(.*?)</h4>')
        result = re.search(pattern,content)
        if result:
            return result.group(1).strip()
        else:
            return None
    #獲取帖子的頁數(shù)
    def get_page_num(self):
        content = self.get_cotent(1)
        pattern = re.compile('<li class="l_reply_num.*?.*?<span.*?>(.*?)',re.S)
        result = re.search(pattern,content)
        if result:
            return result.group(1).strip()
        else:
            return None
    #獲取帖子內(nèi)容
    def get_tiebar(self,page):
        content = self.get_cotent(page).decode('utf-8')
        str = ''
        if not content:
            print "抓取完畢"
            return None
        patt_content = re.compile('<a data-field=.*?class="p_author_name j_user_card".*?>(.*?)</a>.*?'
                    + '<div id=".*?" class="d_post_content j_d_post_content "> '
                    + '(.*?)',re.S)
        msg = re.findall(patt_content,content)
        for item in msg:
            str = str + '\n作者-----' + item[0] + '\n' + '帖子內(nèi)容-----' + item[1].strip() + '\n'
            str = self.tool.replace(str)
            # print u'作者',item[0],u'帖子內(nèi)容:',item[1]
        return str
    #寫文件
    def writeStr2File(self,out_put_file,str1,append = 'a'):
        # 去掉文件,保留路徑。比如 'a/b/c/d.txt' 經(jīng)過下面代碼會變成 'a/b/c'
        subPath = out_put_file[:out_put_file.rfind('/')]
        # 如果給定的路徑中,文件夾不存在,則創(chuàng)建
        if not os.path.exists(subPath):
            os.makedirs(subPath)
        # 打開文件并將 str 內(nèi)容寫入給定的文件
        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"頁數(shù)據(jù)"
        for i in range(1,int(page_num)+1):
            print u"正在寫入第" + str(i) + u"頁數(shù)據(jù)..."
            content = "正在寫入第" + str(i) + u"頁數(shù)據(jù)------------------------------------\n" + self.get_tiebar(i)
            self.writeStr2File(self.out_put_file,content)


class Tool:
    #去除img標(biāo)簽
    patt_img = re.compile(r'<img.*?>')
    patt_herf = re.compile(r'<a.*?>|</a>')
    patt_br = re.compile(r'<br>{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抓取百度貼吧內(nèi)容”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI