1.準(zhǔn)備工作
- 書寫爬蟲之前的步驟:
1.從哪爬 where
2.爬什么 what
3.怎么爬 how
4.爬了之后信息如何保存 save
我稱之為WWHS,這就是最基本的步驟了。
1.1 從哪爬where和爬什么what
其實(shí)where和what是交融的一體,當(dāng)你找到what的時(shí)候,自然就找到了where。當(dāng)你確定了where時(shí),what自然而然就知道了。
這次我們爬取詩詞名句網(wǎng) "http://www.shicimingju.com/" 的名著,如爬取“三國演義”、“隋唐演義”等。-
爬取內(nèi)容如下:
- 主頁面 :[小說名字,每章的名字,每章的鏈接]
- 若干次頁面:[每章的內(nèi)容]
1.2 怎么爬How
1.在主頁面利用正則爬取小說名字存入book_name,然后再爬取每章的名字存入chapter,爬取每章的鏈接存入bookurl。
2.使用for循環(huán)一一使用bookurl[?]來爬取子頁面代碼。
3.利用正則將子頁面代碼中的每章的內(nèi)容爬出來。
A picture is worth a thousand words
1.3 爬了之后信息如何保存
1.小說類型適合使用文件保存,不適合數(shù)據(jù)庫存儲(chǔ)。
2.將book_name作為文件名創(chuàng)建,利用for循環(huán)讀取每章的名字chapter[?]和每章的內(nèi)容chapterText存入文件,形成一個(gè)完整的小說文件。
A picture is worth a thousand words
2.編寫代碼
- 讀取網(wǎng)頁代碼
import urllib.request
import re
indexUrl="http://www.shicimingju.com/book/sanguoyanyi.html"
html =urllib.request.urlopen(indexUrl).read()
html=html.decode('utf8')
- 爬取書名book_name,爬取每章的名字chapter,爬取書的鏈接bookurl
(具體問題具體分析,我這里在爬取每章的鏈接的時(shí)候發(fā)現(xiàn)竟然是相對路徑,無法直接使用,于是只能針對書的鏈接進(jìn)行字符串修改,從而來跳轉(zhuǎn)到每章的頁面。)
book_name=re.findall('<h1>(.*)</h1>',html,re.S)
chapter=re.findall('href="/book/.{0,30}\d\.html">(.*?)</a>',html,re.S)
bookurl=re.findall('href="(/book/.{0,30}\d\.html)">',html,re.S)
chapterUrlBegin=re.sub('.html','',indexUrl)#將書的鏈接替換成每章的鏈接開頭
- 爬取每章的內(nèi)容chapterText,并且輸出成文件。
其中要注意看具體的輸出,替換其中的一些字符和標(biāo)簽。
for i in range(0,len(bookurl)):
#提取每章的number
number=re.findall('/(.{1,4})\.html',bookurl[i])
#合并字符串形成每章的鏈接
chapterUrl=re.sub('$',"/"+number[0]+".html",chapterUrlBegin)
#打開鏈接網(wǎng)頁
chapterHtml=urllib.request.urlopen(chapterUrl).read()
chapterHtml=chapterHtml.decode('utf-8','ignore')
#找到每章內(nèi)容
chapterText=re.findall('<div id="con2".*?>(.*?)</div>',chapterHtml,re.S)
#替換其中的標(biāo)簽<p></p>和 
chapterText=re.sub('<p>','',''.join(chapterText))
chapterText = re.sub('</p>', '', ''.join(chapterText))
chapterText = re.sub('', ' ', ''.join(chapterText))
#輸出文件
f=open('D://book/'+"".join(book_name)+'.txt','a',encoding='utf-8')
f.write(chapter[i]+"\n")
f.write(chapterText+"\n")
f.close()
3.總結(jié)
- 總的過程就一句話:
書寫正則抓取網(wǎng)頁信息,存入數(shù)據(jù)庫或文件。