學習日記 使用BeautifulSoup爬取小說

2021-10-03 20:12:44 字數 3324 閱讀 7883

半個月前入坑了python,近幾天看到csdn上有一些關於美麗的湯(beautifulsoup)的介紹和使用方法,於是自己也試著寫了乙個爬蟲。

小白的學習日記,若有不當之處,歡迎大神們指點!

使用python版本:python3.8

隨便在網上搜了個**,試著爬下來。

**鏈結

檢視網頁的源**,發現文章內容都是p標籤

但是每一章節的url都是不規律的

第一章第二章

所以就把思路轉向了超連結上

在每一章的末尾都有乙個到下一章的超連結

想著用for迴圈,在每爬完一章節之後獲取下一章節的鏈結

nexturl = soup.find(

'a',class_=

'nextchapter'

).attrs[

'href'

] url =

''%(nexturl)

於是乎

#設定需要爬的章數

for i in

range(10

):res = requests.get(url, headers=headers)

#強制轉碼,一開始沒有這行**時輸出的**全是亂碼

res = res.content.decode(

'utf-8'

) soup = beautifulsoup(res,

"html.parser"

)#找到章節的標題

h1 = soup.find(

'h1'

).text

#找到**的內容

novel = soup.find(

'div'

,class_=

'p')

#過濾div標籤中,**後面的廣告

info =

[s.extract(

)for s in novel(

'div')]

info =

[s.extract(

)for s in novel(

'p',class_=

'copy')]

novel = novel.text

print

(novel)

接下來就是把**輸入到文字當中去了

f =

open

('novel.txt'

,'a'

,encoding=

'utf-8'

) f.write(h1+novel)

close操作寫在for迴圈之後

f.close(

)

完整**(附加了乙個計時器,清楚地知道用了多長時間)

# coding=utf-8

#!/usr/bin/env python

from bs4 import beautifulsoup

import requests

import os

import time

url =

''headers =

print

('開始爬取,請等待...'

)start = time.time(

)#爬100章試試

for i in

range

(100):

res = requests.get(url, headers=headers)

res = res.content.decode(

'utf-8'

) soup = beautifulsoup(res,

"html.parser"

) h1 = soup.find(

'h1'

).text

novel = soup.find(

'div'

,class_=

'p')

info =

[s.extract(

)for s in novel(

'div')]

info =

[s.extract(

)for s in novel(

'p',class_=

'copy')]

novel = novel.text

f =open

('我的舌頭變異了.txt'

,'a'

,encoding=

'utf-8'

) f.write(h1+novel)

print

('第%d章爬取完成!'%(

int(i)+1

))nexturl = soup.find(

'a',class_=

'nextchapter'

).attrs[

'href'

] url =

''%(nexturl)

f.close(

)end = time.time(

)process = end - start

print

('全部爬取完成,過程一共耗時%d秒'

%(process)

)

開始執行

結束效果

後端學習日記 MySQL索引的使用

普通索引 alter table table name add index index name column list 唯一索引 alter table table name add unique column list 主鍵索引 alter table table name add primar...

JXL使用日記

建立file檔案物件 file new file generatefilename 建立乙個excel檔案工作物件 excelstore es new excelstore 把file物件連線到excel物件 excelconnection ec es.openconnection file exc...

screen使用日記

screen 使用日記 前言screen 一般用比如putty或xshell 連線伺服器時,開啟的視窗關閉後執行的程序就會結束,若需要保持程序,需要使用screen在screen裡執行程序 yum install screen screen s x 開啟乙個名稱為 某序列.x 的screen 比如s...