利用Python爬取網路小說(基礎)

2021-10-06 10:34:32 字數 1924 閱讀 7586

1.通過requests庫獲取網頁內容

2.通過beautifulsoup庫解析網頁內容

3.在**原始碼裡找到要爬取的內容

4.成功

ps:建議還是學一部分網頁知識之後再來學爬蟲更好理解一些

import requests

import bs4

from bs4 import beautifulsoup

import os

defgethtmltext

(url)

:try

: r = requests.get(url)

"""從伺服器獲取html網頁內容"""

r.raise_for_status(

)"""判斷是否成功獲取"""

return r.text"""返回網頁內容"""

except

:return

"""""

這個函式負責把所有的網頁鏈結儲存進列表中

這裡暫時只儲存前24章的鏈結

"""def

fillweblist

(html,wlist)

: i =

0 soup = beautifulsoup(html,

"html.parser"

)for dd in soup.find(

'dl'

).children:

i = i +

1if i >=24:

ifisinstance

(dd,bs4.element.tag)

:"""判斷屬性是否是標籤"""

dds=dd.contents

link =

""+dds[0]

.attrs[

'href'

]def

enterlink

(ulist)

:"""進入鏈結獲取**內容"""

i =0for link in ulist:

i = i +

1 url = link

html = gethtmltext(url)

soup = beautifulsoup(html,

"html.parser"

)#res = soup.find(id='content')

f =open

("c:/users/聯想/desktop/exa.txt"

,"a+"

,encoding =

'utf-8-sig'

)"""這是我的電腦檔案,不同的電腦檔案路徑不同,需要改"""

f.write(

"第%d章"

%i) f.write(

'\n'

)if i >24:

break

for br in soup.find(id=

'content'

).children:

"""找到id屬性值為content的,並遍歷其所有子元素"""

if br.string is

notnone

:"""判斷是否有字串"""

f.write(br.string)

f.write(

'\n'

)print

("列印成功"

)def

main()

: wlist=

url =

"/5_5731/"

html = gethtmltext(url)

fillweblist(html,wlist)

enterlink(wlist)

大佬勿噴。。。

python爬蟲爬取網路小說

首先,獲取html頁面並解析,為方便儲存和使用頁面的encoding,直接使用全域性變數 章節名章節名 章節名.從結構可以看出,可以先獲取目錄的頂層標籤 class box 的標籤 然後再獲取該標籤內所有的li標籤即可。由於頁面內有其他的class box 的標籤,因此本次使用soup.find s...

Python爬蟲爬取網路小說

太古神王 txt a encoding utf 8 errors ignore i 1while i 2062 single web web file.readline replace n url single web print url header data requests.get url u...

python爬蟲爬網路小說

最近閒的蛋疼想看一些爽文 於是只能自己來爬一篇完整版的 進第一章,檢視源 發現 內容在.裡面 爬內容分了兩步 先爬.裡面的,再爬裡面的。但是不能只爬一章,還要繼續爬,找下一章的鏈結,在下一章裡面 還要爬標題,在裡面 於是分了四個正規表示式 story pattern1 re.compile r re...