当前位置:网站首页>爬虫-爬取某小说网站
爬虫-爬取某小说网站
2022-08-10 08:20:00 【爱学习的Amelia】
- 需求:要爬取某个小说所有章节的网址,再通过爬虫将每一章的内容爬取下来,再本地创建一个文件夹,并且把小说分别保存到这个文件夹中。每一章保存为一个文件。
- 思路:首先是再网址里面获取每一章节的链接,再解析每一个章节的链接中获得文章的标题以及内容,之后再存储。
- 代码如下所示:
import re
import os
import requests
# 获取每一章的链接,拼接成网址
def get_toc(html):
""" 获取每一章的连接存储到一个列表中并返回 :param html:目录页源代码 :return:每章节链接 """
toc_url_list = []
start_url = 'https://www.kanunu8.com/book3/6879/'
toc_block = re.findall('正文(.*?)</tbody>', html, re.S)[0]
toc_url = re.findall('href="(.*?)"', toc_block, re.S)
for url in toc_url:
toc_url_list.append(start_url + url)
return toc_url_list
def get_article(html):
""" 获取每一章的正文并返回章节名和正文 :param html:正文源代码 :return:章节名,正文 """
chapter_name = re.search('size="4">(.*?)<', html, re.S).group(1)
text_block = re.search('<p>(.*?)</p>', html, re.S).group(1)
text_block = text_block.replace('<br />', '')
text_block = re.sub('\r\n\r\n', '\r\n', text_block)
return chapter_name, text_block
# 保存的代码
def save(chapter, article):
""" 将每一章保存到本地。 :param chapter:章节名,第X章 :param article:正文内容 :return:None """
os.makedirs('文件名称', exist_ok=True)
# 如果没有“文件名称”文件夹,就创建一个,图国有,则什么都不做
with open(os.path.join('文件名称', chapter + '.txt'), 'w', encoding='utf-8') as f:
f.write(article)
# 解析网页
html_html = requests.get('目标网址').content.decode('gbk')
strs = get_toc(html_html)
for i in strs:
# 解析内部的每一个小网页
html_each = requests.get(i).content.decode('gbk')
save(get_article(html_each)[0], get_article(html_each)[1])
- 以上代码仅供参考,我爬取的网站为:https://www.kanunu8.com/book3/6879/
边栏推荐
- 速卖通卖家如何抓住产品搜索权重
- debezium-connector-mysql拉起docker报错:debezium启动docke
- Guys, may I ask, the oraclecdc error report is not serialized, but I see that the source code does not inherit serialization, what is the reason?
- IDLE development wordCount program (5)
- 高性能短连接设计
- 明明加了唯一索引,为什么还是产生重复数据?
- 全连接神经网络结构图,神经网络示意图怎么画
- .NET-8. My Thought Notes
- Rust学习:6.5_复合类型之数组
- Day37 LeetCode
猜你喜欢
随机推荐
人工神经网络工作原理,神经网络的工作原理
The probability distribution and its application
UGUI—事件,iTween插件
Quickly enter the current date and time
高性能短连接设计
明明加了唯一索引,为什么还是产生重复数据?
模糊查询除了like+ % 还能用什么方式
Is the write performance of raid5 faster than raid10?
阿里云数据库 RDS SQL Server 版的服务器绑定域名www.cxsdkt.cn.的呢?
神经网络样本太少怎么办,神经网络训练样本太少
自动化测试框架搭建 ---- 标记性能较差用例
PLSQL学习第四天
菜鸟、小白在autojs和冰狐智能辅助之间如何选择?
Based on STC8G2K64S4 single-chip microcomputer to display analog photosensitive analog value through OLED screen
大体来讲,网站会被攻击分为几种原因
同步锁synchronized追本溯源
34. Talk about why you want to split the database?What methods are there?
Add spark related dependencies and packaging plugins (sixth bullet)
NPU architecture and force analysis
Power function Exponential function Logarithmic function