爬蟲(chóng)實(shí)戰(zhàn)1——古詩(shī)

之前在麥子學(xué)院看了黃老師關(guān)于爬蟲(chóng)的基礎(chǔ)課程,自己試著練習(xí)一下,不過(guò)和黃老師的有些區(qū)別,我使用了BeautifulSoup包,等于是改寫(xiě)了一下黃老師的代碼吧。

以下是實(shí)現(xiàn)代碼,直接上干貨


# coding:utf-8

import urllib2,re
from bs4 import BeautifulSoup
import bs4

def retrive_tangshi_300():
    url = 'http://www.gushiwen.org/gushi/tangshi.aspx'
    r = urllib2.urlopen(url)
    soup = BeautifulSoup(r.read(),'html.parser',from_encoding='utf-8')

    # 通過(guò)select選取標(biāo)簽內(nèi)容、地址
    #tags = soup.select('div a')
    #for tag in tags:
    #    print tag['href']

    shige_list = []
    current_poem = {}

    tags = soup.find_all('div', class_ = "guwencont2")
    for tag in tags:
        #print tag.a['href']
        for t in tag.children:
            #print t,type(t)
            if type(t) == bs4.element.Tag:
                pattern = re.compile(r'(.*)\((.*)\)')
                m = pattern.match(t.string)
                if m:
                    current_poem['url'] = t['href']
                    current_poem['title'] = m.group(1)
                    current_poem['author'] = m.group(2)
                    shige_list.append(current_poem)
                    current_poem = {}
    return shige_list



if __name__ == '__main__':
    r = retrive_tangshi_300()
    print 'url: ',r[0]['url'],'\n 作者:',r[0]['author'],'\n 題目:',r[0]['title']
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容