10行Python代码,采集笔趣阁小说!

需要的导入的包:

import requests
import re

爬取笔趣阁小说:

很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取****,电子书籍,以及课程的源代码!??¤
QQ群:961562169

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

最近在看《超神机械师》就以这个为例分析爬取代码

先到小说的详情页面:

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

检索之后可以发现每章小说的网址:

10行Python代码,采集笔趣阁小说!


用re.findall 获取这些网址保存起来待用:

10行Python代码,采集笔趣阁小说!


因为这些网址只是后半部分,我们可以加上后半部分,访问章节网址,获取小说:

10行Python代码,采集笔趣阁小说!


最后保存到文档中就行了:

10行Python代码,采集笔趣阁小说!

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('=====已保存=====')