需求分析
确定采集的URL地址和数据:
目标网站:https://www.jubiquge.com/3072/;
需要采集的数据:小说的章节名称和对应的链接。
采集流程:
首先,采集目录页面的HTML内容,使用正则表达式提取章节名称和链接。
然后,根据提取的链接,采集每个章节的具体内容。
采集目录爬虫:
使用requests库发送GET请求,获取目录页面的HTML内容。
通过正则表达式<a title="(第.*?)"\s+href="(.*?)">提取章节名称和链接。
将提取的数据存储在字典chapter中,并保存到文件丹神目录.txt。
采集章节数据:
从文件丹神目录.txt中加载采集到的目录数据。
遍历目录数据,对每个章节链接发送GET请求,获取章节内容的HTML。
使用正则表达式<div id="content">(.*?)</div>提取章节内容。
清洗数据,去除不必要的HTML标签。
将章节标题和内容保存到文件丹神.txt。
代码呈现
"""
采集目录爬虫
pip install requests
"""
import requests
url = "https://www.jubiquge.com/3072/"
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 SLBrowser/9.0.5.8121 SLBChan/10 SLBVPV/64-bit"
}
# 发起伪造请求
response = requests.get(url, headers=headers)
# 设置响应编码
response.encoding = "UTF-8"
# 查看响应数据
content = response.text
# 正则提取章节名称和连接
import re
# 正则表达式
# <a title="第2章 阴阳神脉" href="/3072/514260.html">第2章 阴阳神脉</a>
p = r'<a title="(第.*?)"\s+href="(.*?)">'
# 全部匹配的方式提取数据
chs = re.findall(p, content, re.DOTALL)
# print(chs)
chapter = dict()
for ch in chs:
chapter[ch[0]] = "https://www.jubiquge.com" + ch[1]
# 最终章节和链接数据
# print(chapter)
# 文件IO中保存目录数据
import json
with open("丹神目录.txt", mode="wt", encoding="utf-8") as file:
json.dump(chapter, file)
"""
采集章节数据
"""
import requests, re
import time, random
import json
# 1. 加载需要采集的目录
with open("丹神目录.txt", encoding="UTF-8") as file:
chs = json.load(file)
# print(chs)
# 2. 循环遍历,发起伪造请求
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 SLBrowser/9.0.5.8121 SLBChan/10 SLBVPV/64-bit"
}
for title, url in chs.items():
print(f"准备采集: {title}")
# 发起伪造请求
response = requests.get(url, headers=headers)
# # 设置编码
response.encoding = "UTF-8"
# 分析数据格式
html = response.text
# print(html)
# def replace_invalid_chars(text):
# return text.encode('gbk', 'replace').decode('gbk')
# print(replace_invalid_chars(html))
print("----------------------")
# 定义正则,匹配数据<div id="content" style="font-family: null;">
p = r'<div id="content">(.*?)</div>'
content1 = re.findall(p, html, re.DOTALL)
print(content1)
# content = re.search(p, html)
# # 数据筛选
# content = content.group(1).strip()
# # 数据清洗
# p2 = r'<p>(.*?)</p>'
# content = re.findall(p2, content, re.DOTALL)
# content = "\n".join(content)
# print(content)
# # 保存到文件
# with open("丹神.txt", mode="at", encoding="utf-8") as file:
# file.write("\n\n-----------------------\n\n")
# file.write("\n\n" + title + "\n\n") # 标题
# file.write(content) # 内容
# 模拟用户请求,每次请求完成休眠3~5S
time.sleep(random.randint(3, 5))
print(f"{title} 章节采集完成")
# 测试,采集一次数据
# break
结果呈现