1. 程式人生 > 實用技巧 >10行Python程式碼,採集筆趣閣小說!

10行Python程式碼,採集筆趣閣小說!

需要的匯入的包:

import requests
import re

爬取筆趣閣小說:

很多人學習python,不知道從何學起。
很多人學習python,掌握了基本語法過後,不知道在哪裡尋找案例上手。
很多已經做案例的人,卻不知道如何去學習更加高深的知識。
那麼針對這三類人,我給大家提供一個好的學習平臺,免費領取視訊教程,電子書籍,以及課程的原始碼!??¤
QQ群:961562169

https://www.biquge.com.cn/

最近在看《超神機械師》就以這個為例分析爬取程式碼

先到小說的詳情頁面:

https://www.biquge.com.cn/book/29105/

檢索之後可以發現每章小說的網址:


用re.findall 獲取這些網址儲存起來待用:


因為這些網址只是後半部分,我們可以加上後半部分,訪問章節網址,獲取小說:


最後儲存到文件中就行了:

import requests
import re
#請求頭
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7',
    'Referer': 'https://www.biquge.com.cn/'
}
#網址
url = 'https://www.biquge.com.cn/book/29105/'
urls = 'https://www.biquge.com.cn'
#獲取text
req = requests.get(url,headers = headers)
html = req.text
#獲取每章節的網址
zhangjie = re.findall('<dd><a href="(.*?)"  >.*?</a></dd>',html,re.S)
mulu = re.findall('<dd><a href=".*?"  >(.*?)</a></dd>',html,re.S)

i = 0
for url in zhangjie:
    requ = requests.get(urls+url,headers = headers)
    htmls = requ.text
    #獲取小說文字
    fiction = re.findall('<div id="content">&nbsp;&nbsp;&nbsp;&nbsp;(.*?)</div>',htmls,re.S)
    fiction = str(fiction)
    #消去多餘字元
    fiction = re.sub("[|]|<br><br>&nbsp;&nbsp;&nbsp;&nbsp;|<br>",'',fiction)
    print(mulu[i])
    print('======儲存中======')
    #儲存到文字中
    print(fiction[2:-2])
    with open('超神機械師1.txt','a+') as f:
        fictions = str(mulu[i]) + '\n' +fiction[2:-2]+'\n'
        f.writelines(str(fictions))
        i +=1
        print('=====已儲存=====')