当前位置:网站首页>爬虫-爬取某小说网站
爬虫-爬取某小说网站
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/
边栏推荐
- UGUI—事件,iTween插件
- day16--抓包工具Charles的使用
- Different command line styles
- Uni-app开发微信小程序使用本地图片做背景图
- 大体来讲,网站会被攻击分为几种原因
- m.bjhjwy.com全面教学设备 类型包括: 教学仪器, 教学设备 ,
- VS2013-调试汇编代码-生成asm文件-结构体内存布局-函数参数压栈-调用约定
- VS2013-debug assembly code-generate asm file-structure memory layout-function parameter stack-calling convention
- 问下cdc mysql to doris.不显示具体行数,怎么办?
- 一文2600字手把手教你编写性能测试用例
猜你喜欢

Add spark related dependencies and packaging plugins (sixth bullet)

The sixteenth day & the basic operation of charles

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

每日一题,数组字符串的匹配问题

PLSQL学习第三天

2022-08-01 网工进阶(二十四) STP进阶知识

时序动作定位 | ASM-Loc:弱监督时序动作定位的动作感知片段建模(CVPR 2022)

ABAP Data Types 和XSD Type 映射关系以及XSD Type属性

快速输入当前日期与时间

本地生活商家如何通过短视频赛道,提升销量曝光量?
随机推荐
明明加了唯一索引,为什么还是产生重复数据?
day16--抓包工具Charles的使用
UGUI—事件,iTween插件
图像处理用什么神经网络,神经网络提取图片特征
Synchronization lock synchronized traces the source
QT下载清华源配置
问下cdc mysql to doris.不显示具体行数,怎么办?
AFNetworking概述和4.0的实践
Solve the problem that the win10win7win8 system cannot find the specified module and cannot register the desert plug-in
How AliExpress sellers seize product search weight
The implementation of the seemingly useless component (text gradient) in NaiveUI is so simple
TensorFlow 2.9的零零碎碎(一)
自动化测试框架Pytest(二)——前后置处理
解决win10win7win8系统找不到指定的模块,注册不了大漠插件的问题
[机缘参悟-65]:《兵者,诡道也》-7-三十六计解读-败战计
每日一题,数组字符串的匹配问题
差分、前缀和模板
大佬们,请问一下,oraclecdc报错没有序列化,可是我看源码中的确是没有继承序列化的,是什么原因
iwemeta元宇宙:一个娃娃卖9999元,泡泡玛特认为一点也不贵
VS2013-调试汇编代码-生成asm文件-结构体内存布局-函数参数压栈-调用约定