当前位置:网站首页>爬虫-爬取某小说网站
爬虫-爬取某小说网站
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/
边栏推荐
- 数据库公共字段自动填充
- 时序动作定位 | ASM-Loc:弱监督时序动作定位的动作感知片段建模(CVPR 2022)
- 明明加了唯一索引,为什么还是产生重复数据?
- 高性能短连接设计
- winget package manager
- Synchronization lock synchronized traces the source
- C# 获取PCI等设备的插槽位置信息
- 组合数模板
- Relaxation class: the boss will martial arts, who also can not hold up against!The charm of six sigma training
- 如何远程调试对方的H5页面
猜你喜欢

Process management (dynamic)

颜色选择器的使用

自动化测试框架Pytest(二)——前后置处理

iwemeta元宇宙:一个娃娃卖9999元,泡泡玛特认为一点也不贵

PLSQL学习第一天

明明加了唯一索引,为什么还是产生重复数据?

iwemeta metaverse: a doll sells for 9999 yuan, and Bubble Mart thinks it is not expensive at all

什么是长轮询

Quickly enter the current date and time

day16--The use of the packet capture tool Charles
随机推荐
The sixteenth day & the basic operation of charles
PHP笔记 28 29 30 31
差分、前缀和模板
Introduction to the delta method
day16--抓包工具Charles的使用
CV-人脸识别-2018:ArcFace
手把手教你进行Mysql查询操作
.NET-8. My Thought Notes
机器人控制器编程实践指导书旧版-实践二 传感器(模拟量)
模糊查询除了like+ % 还能用什么方式
QT下载清华源配置
Quickly enter the current date and time
Using the color picker
SQL建表问题,帮我看看好吗朋友们~大家人。!
A File Online Query Display and Download Function Realized by Delphi
机器人控制器编程实践指导书旧版-实践一 LED灯(数字量)
如何设计神经网络结构,神经网络设计与实现
大佬们,请问一下,oraclecdc报错没有序列化,可是我看源码中的确是没有继承序列化的,是什么原因
winget包管理器
VS2013-debug assembly code-generate asm file-structure memory layout-function parameter stack-calling convention