第一天重拾信心開始學習爬蟲。這是看了簡書一位作者的文章感覺很詳細,參照人家的文章自己跑了一遍。
原文連結為:http://www.jianshu.com/p/23070977f63c
首先安裝好bs4,
import urllib.request>>> import chardet>>> from bs4 import BeautifulSoup>>> url="http://www.shicimingju.com/book/sanguoyanyi.html"#要爬取的網路地址>>> menuCode=urllib.request.urlopen(url).read()#將網頁原始碼賦予menuCode#使用bs4處理後得到整個頁面的soup和要找的部分soup2>>> soup=BeautifulSoup(menuCode,"html.parser")#使用html解析器進行解析>>> menu=soup.find_all(id="mulu")#在soup中找到id為mulu的節點>>> values=",".join(str(v) for v in menu)#將menu轉換為str類型>>> soup2=BeautifulSoup(values,"html.parser");>>> soup2=soup2.ul#用子節點代替soup2>>> bookName=soup.h1.string#找到了書名>>> f=open("bookName.txt","a",encoding="utf8")#爬取章節url,並解決url為本地的問題>>> bookMenu=[]#章節list>>> bookMenuUrl=[]#章節url的list
>>> for i in range(1,len(soup2.contents)-1):#依次爬取所有章節bookMenu.append(soup2.contents[i].string)bookMenuUrl.append(soup2.contents[i].a["href"])
依次爬取每章內容並寫入txt
>>> urlBegin="http://www.shicimingju.com"#解決url為本地的問題>>> for i in range(0,len(bookMenuUrl)):#依次替換url,讀取每章頁面的內容chapterCode=urllib.request.urlopen(urlBegin+bookMenuUrl[i]).read()result=chardet.detect(chapterCode)#檢驗讀取的頁面的編碼方式if(result["confidence"]>0.5):#如果機率大於0.5,採取這種編碼方式chapterCode=chapterCode.decode(result["encoding"])chapterSoup=BeautifulSoup(chapterCode,"html.parser")#使用BS讀取解析網頁代碼chapterResult=chapterSoup.find_all(id="con2")#找到id=“con2”的節點,可以點擊第一回內容的網站上自己查看chapterResult=",".join(str(v) for v in chapterResult)chapterSoup2=BeautifulSoup(chapterResult,"html.parser")chapterSoup2=chapterSoup2.brf.write(bookMenu[i])#寫入檔案的每章標題for j in range(0,len(chapterSoup2)):#迴圈寫入每章內容chapterText=chapterSoup2.contents[j].stringf.write(chapterText)
整個爬蟲結束後,是一本《三國演義》的書。對於這碗美麗的湯,不需要我們用Regex,只用根據節點進行查詢就可以了。