嗨喽~大家好呀,这里是魔王呐 ❤ ~!
python更多源码/资料/解答/教程等 点击此处跳转文末名片免费获取
很多小伙伴学习Python的初衷就是为了爬取小说,方便又快捷~
辣么今天咱们来分享6个主流小说平台的爬取教程~
一、流程步骤
流程基本都差不多,只是看网站具体加密反爬,咱们再进行解密。
实现爬虫的第一步?
1、去抓包分析,分析数据在什么地方。
-
打开开发者工具
-
刷新网页
-
找数据 --> 通过关键字搜索
2、获取小说内容
-
目标网址
-
获取网页源代码请求小说链接地址,解析出来
-
请求小说内容数据包链接:
-
获取加密内容 --> ChapterContent
-
进行解密 --> 分析加密规则 是通过什么样方式 什么样代码进行加密
3、获取响应数据
response.text 获取文本数据 字符串
response.json() 获取json数据 完整json数据格式
response.content 获取二进制数据 图片 视频 音频 特定格式文件
二、案例
1、书旗
环境使用:
-
Python 3.8
-
Pycharm
模块使用:
- requests
- execjs
- re
源码展示:
# 导入数据请求模块
import requests
# 导入正则模块
import re
import execjs
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:926207505
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# 模拟浏览器
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.3'
}
# 请求链接 -> 目录页面链接
html = '网址屏蔽了,不然过不了'
# 发送请求
html_ = requests.get(url=html, headers=headers).text
# 小说名字
name = re.findall('<title>(.*?)-书旗网</title>', html_)[0]
# 提取章节名字 / 章节ID
info = re.findall('data-clog="chapter\$\$chapterid=(\d+)&bid=8826245">\d+\.(.*?)</a>', html_, re.S)
print(name)
# for 循环遍历
for chapter_id, index in info:
title = index.strip()
print(chapter_id, title)
# 请求链接
url = f'https://网址屏蔽了,不然过不了/reader?bid=8826245&cid={
chapter_id}'
# 发送请求 <Response [200]> 响应对象
response = requests.get(url=url, headers=headers)
# 获取响应数据
html_data = response.text
# 正则匹配数据
data = re.findall('contUrlSuffix":"\?(.*?)","shelf', html_data)[0].replace('amp;', '')
# 构建小说数据包链接地址
link = 'https://c13.网址屏蔽了,不然过不了.com/pcapi/chapter/contentfree/?' + data
# 发送请求
json_data = requests.get(url=link, headers=headers).json()
# 键值对取值, 提取加密内容
ChapterContent = json_data['ChapterContent']
# 解密内容 --> 通过python调用JS代码, 解密
f = open('书旗.js', encoding='utf-8')
# 读取JS代码
text = f.read()
# 编译JS代码
js_code = execjs.compile(text)
# 调用Js代码函数
result = js_code.call('_decodeCont', ChapterContent).replace('<br/><br/>', '\n').replace('<br/>', '')
# 保存数据
with open(f'{name}.txt', mode='a', encoding='utf-8') as v:
v.write(title)
v.write('\n')
v.write(result)
v.write('\n')
print(json_data)
print(ChapterContent)
print(result)
效果展示:
2、塔读
环境使用:
-
Python 3.8
-
Pycharm
模块使用:<