python爬蟲得到《三國演義》

來源:互聯網
上載者:User

第一天重拾信心開始學習爬蟲。這是看了簡書一位作者的文章感覺很詳細,參照人家的文章自己跑了一遍。

原文連結為: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,只用根據節點進行查詢就可以了。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.