需要的导入的包:
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"> (.*?)</div>',htmls,re.S)
fiction = str(fiction)
#消去多余字符
fiction = re.sub("[|]|<br><br> |<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('=====已保存=====')
本文介绍如何使用Python进行网络爬虫,以笔趣阁小说《超神机械师》为例,通过导入requests和re库,解析小说详情页URL,提取章节链接并访问获取内容,最终将小说保存到文档中。
2096

被折叠的 条评论
为什么被折叠?



