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

python批量下载csdn文章

声明:该爬虫只可用于提高自己学习、工作效率,请勿用于非法用途,否则后果自负

功能概述:

  1. 根据待爬文章url(文章id)批量保存文章到本地;
  2. 支持将文中图片下载到本地指定文件夹;
  3. 多线程爬取;

1.爬取效果展示

本次示例爬取的链接地址:
https://blog.csdn.net/m0_68111267/article/details/132574687

原文效果:

爬取效果:

文件列表:

2.编写代码

爬虫使用scrapy框架编写,分布式、多线程

2.1编写Items

class ArticleItem(scrapy.Item):id = scrapy.Field()  # IDtitle = scrapy.Field()html = scrapy.Field()  # htmlclass ImgDownloadItem(scrapy.Item):img_src = scrapy.Field()img_name = scrapy.Field()image_urls = scrapy.Field()class LinkIdsItem(scrapy.Item):id = scrapy.Field()

2.2添加管道

class ArticlePipeline():def open_spider(self, spider):if spider.name == 'csdnSpider':data_dir = os.path.join(settings.DATA_URI)#判断文件夹存放的位置是否存在,不存在则新建文件夹if not os.path.exists(data_dir):os.makedirs(data_dir)self.data_dir = data_dirdef close_spider(self, spider):  # 在关闭一个spider的时候自动运行pass# if spider.name == 'csdnSpider':#     self.file.close()def process_item(self, item, spider):try:if spider.name == 'csdnSpider' and item['key'] == 'article':info = item['info']id = info['id']title = info['title']html = info['html']f = open(self.data_dir + '/{}.html'.format(title),'w',encoding="utf-8")f.write(html)f.close()except BaseException as e:print("Article错误在这里>>>>>>>>>>>>>", e, "<<<<<<<<<<<<<错误在这里")return item

2.3添加配置

2.4添加解析器

...def parse(self, response):html = response.bodya_id = response.meta['a_id']soup = BeautifulSoup(html, 'html.parser')[element.extract() for element in soup('script')][element.extract() for element in soup.select("head style")][element.extract() for element in soup.select("html > link")]# 删除style中包含隐藏的标签[element.extract() for element in soup.find_all(style=re.compile(r'.*display:none.*?'))]...

3.获取完整源码

项目说明文档

爱学习的小伙伴,本次案例的完整源码,已上传微信公众号“一个努力奔跑的snail”,后台回复“csdn”即可获取。

源码地址:

https://pan.baidu.com/s/1uLBoygwQGTSCAjlwm13mog?pwd=****

提取码: ****

http://www.xdnf.cn/news/833689.html

相关文章:

  • OpenGLES系列demo之框架简介
  • C++中istringstream、ostringstream、stringstream 的用法
  • 《apue》 首次拜读完经典之作,两三记录
  • 【知识整理】MySQL数据库开发设计规范
  • parentNode和offsetParent的使用
  • simulink仿真技术简介
  • 延迟加载(Lazyload)三种实现方式
  • 2024年最全速看!成为黑k必看13个网站,简称网站大全!_红黑联盟官方网站,2024年最新看看这篇文章吧
  • log4cpp初入门
  • linux查看7799端口使用情况,OEM12C安装文档
  • 使用Flash_TooL软件刷机Android 手机步骤
  • ADODB 使用说明
  • Manifest文件详解
  • IF函数超实用的12种经典用法
  • 函数PostEvent、triggerevent详解
  • 八款好用的浏览器兼容性测试工具推荐
  • 【深度学习】【机器学习】用神经网络进行入侵检测,NSL-KDD数据集,基于机器学习(深度学习)判断网络入侵,网络攻击,流量异常
  • 想染指系统架构?看这篇就够了
  • DevC++graphics.h库(1)库的下载与安装
  • 【windows】--- SQL Server 2008 超详细安装教程
  • 在 SpringBoot 中使用 ThreadPoolTaskScheduler 实现定时任务
  • 一位十年软件工程师告诉你什么是编程思想
  • 【最新】网站下载工具,整站下载工具汇总
  • 原生js中nextSibling和nextElementSibling的坑
  • 如何执行VMware P2V迁移|VMware Converter和替代方案
  • CppCon 2014 学习:Rolling Your Own Circuit Simulator
  • 工作中使用到的单词(软件开发)_第二版
  • 弱口令(Weak Password)总结和爆破工具
  • arm9芯片包括哪些?arm9如何应用
  • pascal编程语言介绍