用python爬取小說章節內容

2022-08-29 14:09:24 字數 1943 閱讀 2103

在學爬蟲之前, 最好有一些html基礎, 才能更好的分析網頁. 

主要是五步:

1.  獲取鏈結

2. 正則匹配

3. 獲取內容

4. 處理內容

5. 寫入檔案

**如下:

#匯入相關model

2from bs4 import

beautifulsoup

3import

requests

4importre5

6#獲取目標鏈結位址

7 url = '

'8 reponse =requests.get(url)

9 reponse.encoding = '

gbk'

#設定編碼方式,可在網頁原始碼頭部查到

10 html =reponse.text

1112

#獲取各章節鏈結和標題13#

審查元素, 找到**章節的**位置, 找出其對應的標籤, 進行正則匹配

14 dl = re.findall(r'

(.*?)

', html, re.s) #

返回list型別

15 j=0 #

計數, 只獲取前30章, 多了結果要很久才出來

1617

#進行章節內容獲取

18for chapter in

dl:19

if j >= 30:

20break21#

獲取章節鏈結,名字.等價於c_link=chapter[0]; c_title=chapter[1]

22 chapter_link, chapter_title =chapter23#

補全鏈結,因為之前獲取的只是鏈結的尾部

24 chapter_link = "

" %chapter_link

2526

#仿照之前的再寫一遍

27 chapter_reponse =requests.get(chapter_link)

28 chapter_reponse.encoding='

gbk'

29 chtml =chapter_reponse.text30#

找到**章節正文所在標籤

31 chapter_content = re.findall(r'

(.*?)

', chtml,re.s)32#

將它們轉換為字串,因為list無法進行replace操作

33 t =str(chapter_title)

34 s =str(chapter_content)35#

替代好空格,換行, 以及列表的左右中括號

36 s = s.replace('

','').replace('

',"\n

").replace('

\\r\\n

',''

)37 s = s.replace('

]',"

\n").replace('

[','

').replace38#

新建txt檔案,並將其名字設定為章節名, 寫入

39 f = open('

e:/temp/zhuxian/%s.txt

' % chapter_title, 'w'

)40f.write(t)

41 f.write('\n'

)42f.write(s)

43 j = j+1

44print('ok'

)45f.close()

46'''

s = s.replace('[','')

47s = s.replace('

',"\n")

48s = s.replace('\\r\\n','')

'''

用python爬取小說章節內容

在學爬蟲之前,最好有一些html基礎,才能更好的分析網頁.主要是五步 1.獲取鏈結 2.正則匹配 3.獲取內容 4.處理內容 5.寫入檔案 如下 匯入相關model from bs4 import beautifulsoup import requests import re 獲取目標鏈結位址 ur...

Python爬取小說 2 單章節爬取

coding utf 8 urlopen 開啟 request 請求 from urllib.request import urlopen,request 匯入gzip包 解壓gzip 封裝請求 req request url path,headers headers 開啟鏈結 conn urlop...

request爬取小說內容

request爬取 內容 import re import requests import os bookurl 書的位址 booksite requests.get bookurl 獲取書的網頁 booksite.encoding gbk book name re.findall booksite...