python爬蟲之小說爬取

來源:互聯網
上載者:User

標籤:中文   對象   com   起點中文   觀察   引入   封裝   今天   文字   

廢話不多說,直接進入正題。

今天我要爬取的網站是起點中文網,內容是一部小說。

首先是引入庫

from urllib.request import urlopenfrom bs4 import BeautifulSoup

然後將網址賦值

html=urlopen("http://read.qidian.com/chapter/dVQvL2RfE4I1/hJBflakKUDMex0RJOkJclQ2.html")  //小說的第一章的網址bsObj=BeautifulSoup(html)                                                                 //建立beautifulsoup對象

首先嘗試爬取該頁的小說內容

firstChapter=bsObj.find("div",{"class","read-content"})                                 //find方法是beautifulsoup對象擁有的函數,print (firstChapter.read_text())

find方法也可以和Regex搭配使用,並且多用於圖片,視頻等資源的爬取

 

由於本次爬取內容全在一個class屬性值為read-content的盒子中,所以採用了find方法,如果該網頁中,文字被放在多個盒子裡,則應採用findAll方法,並且傳回值為一個集合,需要用迴圈遍曆輸出。

將代碼整合運行,發現可以實現文章的爬取,但是現在的問題是,爬取了該小說的一章,那麼,往後的幾章該如何爬取呢?

由前面步驟可以得出,只要得知下一章的網址,即可進行爬取。首先,將列印文字的部分封裝為函數,那麼,每次取得新的地址,即可列印出對應文本

def writeNovel(html):    bsObj=BeautifulSoup(html)    chapter=bsObj.find("div",{"class","read-content"})    print (chapter.get_text())

現在的問題是如何爬取下一章的網址,觀察網頁結構可得知,下一章的按鈕實質是一個id為j_chapterNext的a標籤,那麼,可由這個標籤獲得下一章的網址

重新封裝函數,整理得:

from urllib.request import urlopen
from bs4 import BeautifulSoup
def writeNovel(html):
bsObj=BeautifulSoup(html)
chapter=bsObj.find("div",{"class","read-content"})
print (chapter.get_text())
bsoup=bsObj.find("",{"id":"j_chapterNext"})
html2="http:"+bsoup.get(‘href‘)+".html"
return (urlopen(html2))

html=urlopen("http://read.qidian.com/chapter/dVQvL2RfE4I1/hJBflakKUDMex0RJOkJclQ2.html")

i=1
while(i<10):
   html=writeNovel(html)
   i=i+1

 將文本寫入text檔案中

from urllib.request import urlopenfrom bs4 import BeautifulSoupdef writeNovel(html):    bsObj=BeautifulSoup(html)    chapter=bsObj.find("div",{"class","read-content"})    print (chapter.get_text())    fo=open("novel.text","a")    fo.write(chapter.get_text())    fo.close    bsoup=bsObj.find("",{"id":"j_chapterNext"})    html2="http:"+bsoup.get(‘href‘)+".html"    return (urlopen(html2))html=urlopen("http://read.qidian.com/chapter/dVQvL2RfE4I1/hJBflakKUDMex0RJOkJclQ2.html")  i=1while(i<8):    html=writeNovel(html)    i=i+1

 

python爬蟲之小說爬取

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.