当前位置: 首页 > news >正文

趣笔阁爬虫实验

趣笔阁爬虫实验

用BeautifulSoup解析网页结构,爬取指定小说的页面,将每个章节的内容保存到txt文件中

可以改进的点:(待更新

1.反爬措施

2.多线程

3.保存为markdown格式更加美观

import os
import re
import requests
from bs4 import BeautifulSoup
import time
def getHtml(url, param=None, encoding=None):# 获取url内的html文本内容try:# 构造访问头header = {'user-agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"}# 获取返回html = requests.get(url, headers=header, timeout=10)# 定义编码方式if encoding is None:encoding = html.apparent_encodinghtml.encoding = encoding# 保存html文本content = html.text# 关闭连接html.close()# 间隔1s 防止过快访问time.sleep(1)# 返回网页内容return contentexcept requests.RequestException as e:print(f"请求失败: {e}")return None  # 返回None表示失败def getLink(content):soup = BeautifulSoup(content, "html.parser")res = []# 查找所有章节标题的标签titles = soup.find_all('dd')# 提取每个章节的文本for title in titles:a_tag = title.find('a')if a_tag:name = a_tag.textres.append(name)print(res)return resdef save(name, passage_content, path):# 定义文件路径,文件名使用章节名称file_path = os.path.join(path, f"{name}.txt")# 将连续空格替换为换行符,并将其写入文件with open(file_path, 'w', encoding='utf-8') as file:for content in passage_content:# 替换连续空格为换行符formatted_content = re.sub(r'\s{2,}', '\n', content.text)file.write(formatted_content + "\n")  # 额外加上换行符,使得段落更清晰print(f"章节 {name} 已保存")
def saveImg(title,imgLink,path):# 定义文件路径,文件名使用章节名称file_path = os.path.join(path, f"{title}.jpg")response = requests.get(imgLink)# 将连续空格替换为换行符,并将其写入文件if response.status_code == 200:with open(file_path, 'wb') as file:file.write(response.content)  # 额外加上换行符,使得段落更清晰print(f"图片 {title} 已保存")else:print(f"图片 {title} 保存失败")def getMain(content):soup = BeautifulSoup(content, "html.parser")name = ''titles = soup.find_all('div',attrs={"class":"info"})# 提取每个章节的文本for title in titles:img_tag = title.find('img')img = img_tag['src']# print(img_tag['src'])name = img_tag['alt']# print(img_tag['alt'])return name,imgdef getConcent(root,titles,path):pat = re.compile(r'第(.*?)章')for title in titles:res = pat.search(title)if res:print(res.groups())page = res.group(1)url = root + page + ".html"content = getHtml(url)soup = BeautifulSoup(content, "html.parser")# print(content)passage = []passage_content = soup.find_all("div",attrs={"id":"chaptercontent"})for item in passage_content:passage.append(item.text)print(item.text)print(markdownify.markdownify(item.text))# print(passage_content)save(title, passage_content, path)
if __name__ == "__main__":try:# 目标贴吧url = "https://www.3bqg.cc/book/152484/"# 目标输出csv文件路径path = "./novel/"# 获取目标网页的源码content = getHtml(url)title,img = getMain(content)saveImg(title,img,path+title)titles = getLink(content)getConcent(url,titles,path+title)except Exception as e:print(f"程序运行出错: {e}")

相关文章:

  • 华为eNSP使用详解
  • vue-cli,element-plus,axios,proxy
  • docker-图形化工具-portainer的使用
  • NXP i.MX8系列平台开发讲解 - 4.2.2 摄像头篇(二) - 摄像头DVP接口
  • PG逻辑订阅功能
  • 【Mysql多数据源实现读写分离的几种方案】
  • 【网站架构部署与优化】Tomcat部署安装
  • android设计模式的建造者模式,请举例
  • Tesla T4 P2P测试
  • Apache Iceberg 与 Spark整合-使用教程(Iceberg 官方文档解析)
  • 重头开始嵌入式第四十二天(硬件 ARM体系架构)
  • 计算机网络(八) —— Udp协议
  • powershell@update-help更新文档和离线文档安装@并行加速安装帮助文档更新@安装报错问题
  • 【LeetCode:219. 存在重复元素 II + 哈希表】
  • Ant design vue中的提示框(a-tooltip)
  • (十五)java多线程之并发集合ArrayBlockingQueue
  • 2019年如何成为全栈工程师?
  • Android组件 - 收藏集 - 掘金
  • angular学习第一篇-----环境搭建
  • CSS实用技巧干货
  • ECS应用管理最佳实践
  • java2019面试题北京
  • Java知识点总结(JavaIO-打印流)
  • JS+CSS实现数字滚动
  • Js基础知识(四) - js运行原理与机制
  • Mysql数据库的条件查询语句
  • PHP面试之三:MySQL数据库
  • React as a UI Runtime(五、列表)
  • redis学习笔记(三):列表、集合、有序集合
  • swift基础之_对象 实例方法 对象方法。
  • vue从入门到进阶:计算属性computed与侦听器watch(三)
  • 大数据与云计算学习:数据分析(二)
  • 读懂package.json -- 依赖管理
  • 机器学习学习笔记一
  • 解决iview多表头动态更改列元素发生的错误
  • 视频flv转mp4最快的几种方法(就是不用格式工厂)
  • 我这样减少了26.5M Java内存!
  • 小程序上传图片到七牛云(支持多张上传,预览,删除)
  • 移动端解决方案学习记录
  • 扩展资源服务器解决oauth2 性能瓶颈
  • # 利刃出鞘_Tomcat 核心原理解析(七)
  • $(selector).each()和$.each()的区别
  • (2024,Flag-DiT,文本引导的多模态生成,SR,统一的标记化,RoPE、RMSNorm 和流匹配)Lumina-T2X
  • (23)Linux的软硬连接
  • (3)医疗图像处理:MRI磁共振成像-快速采集--(杨正汉)
  • (5)STL算法之复制
  • (TOJ2804)Even? Odd?
  • (备忘)Java Map 遍历
  • (附源码)springboot家庭财务分析系统 毕业设计641323
  • (附源码)计算机毕业设计ssm高校《大学语文》课程作业在线管理系统
  • (剑指Offer)面试题41:和为s的连续正数序列
  • (三维重建学习)已有位姿放入colmap和3D Gaussian Splatting训练
  • (淘宝无限适配)手机端rem布局详解(转载非原创)
  • (一)为什么要选择C++
  • (转载)VS2010/MFC编程入门之三十四(菜单:VS2010菜单资源详解)