写完博客文章后,再给爬下来,保存在本地~ 哈阿哈
写完博客文章后,再给爬下来,保存在本地~ 哈阿哈
为什么不直接CV呢?那还是爬取比CV快呀~傻瓜
继上次爬取了博主的文章列表后,再做下载保存文章。搜索引擎 查询后,果然没有python办不到的事,借鉴代码后。增加了,对文章中的图片下载至本地
文章地址:爬取CSDN博主文章列表,练习
源码
import parsel, tomd, re
# pip install tomd -i https://pypi.tuna.tsinghua.edu.cn/simple
from module_path import util, logging# 把文章保存为markdown
def download_article(url):try:html = util.get_html(url)# 把网页变成css选择器,解析网页sel = parsel.Selector(html)# 标题,内容title = sel.css('.title-article::text').get()content = sel.css('article').get()# 提取文章的内容与格式text = tomd.Tomd(content).markdowntext = re.sub('<article.*?article>', "", text)# 获取后,标题中带有<a>..</a>的去掉text = re.sub('<a.*</a>', "", text)"""将图片下载 下来,替换文章中的csdn链接"""imgs = re.findall('<img.*?>', text)root_path = util.JarProjectPath.project_root_path()# 创建文件夹folder = util.mkdir(path='%s/files/%s'%(root_path, title))for i in range(len(imgs)):# 获取图片地址url = re.search(r'.*src="(.*?)"', imgs[i]).group(1)# print(imgs[i])# 下载图片,返回本地路径filepath = util.download_img(url, filename='%s_%d'%(title, i), filedir=folder)# 替换文章中的链接text = text.replace(imgs[i], '<img src="%s" >'%filepath)# 保存文章路径filename = '%s/files/%s.md'%(root_path, title)# 保存with open(filename, mode='w', encoding='utf-8') as f:f.write("#" + title)f.write(text)except Exception as e:logging.debug(e)print('失败>%s'%url)if __name__ == '__main__':# 博客地址url,问号后的参数可以都删掉url = 'https://blog.csdn.net/qq_39454665/article/details/120507437'download_article(url)
其中,使用tomd 获取后,标题中会多出<a>...</a>
的内容,再用正则替换掉,或者打开文件手动删除
# 提取文章的内容与格式text = tomd.Tomd(content).markdowntext = re.sub('<article.*?article>', "", text)# 获取后,标题中带有<a>..</a>的去掉text = re.sub('<a.*</a>', "", text)
源代码中有
不处理,保存后,影响MD格式之美
工具类Util
# 获取请求头
def get_headers(localhost=True, refer="https://www.baidu.com", host=None):ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"if not localhost:uas = ["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36","Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)","Mozilla/5.0 (compatible; Baiduspider-render/2.0; +http://www.baidu.com/search/spider.html)","Baiduspider-image+(+http://www.baidu.com/search/spider.htm)","Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)","Mozilla/5.0 (compatible; Googlebot-Image/1.0; +http://www.google.com/bot.html)","Sogou web spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07)","Sogou News Spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07)","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0);","Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)","Sosospider+(+http://help.soso.com/webspider.htm)","Mozilla/5.0 (compatible; Yahoo! Slurp China; http://misc.yahoo.com.cn/help.html)"]ua = random.choice(uas)headers = {"User-Agent": ua,"Referer": refer,"Host": host}return headers# 获取html
def get_html(url, ret_type="text", timeout=50, encoding="utf-8"):headers = get_headers()res = requests.get(url, headers=headers, timeout=timeout)res.encoding = encoding# print(res.status_code)# print(res.text)if ret_type == "text":return res.textelif ret_type == "image":return res.contentelif ret_type == "json":return res.json()# 创建文件夹
def mkdir(path=os.path.join(__dir__, '../images/%s'%str(round(time.time() * 1000)) + '/')):"""新建图片文件夹:param path: The file path - 文件路径 """ext = os.path.exists(path)#判断是否存在文件夹如果不存在则创建为文件夹if not ext:os.makedirs(path)print ("--- new folder... ---", path)#else:#print ("--- There is this folder! ---")return '%s/'%pathdef download_img(src, filename=str(round(time.time() * 1000)), filedir=os.path.join(__dir__, '../images/'), domain=None):"""图片下载:param src: The image http url - 图片链接:param filename: file name - 名称。默认当前时间戳:param filedir: file saved dir - 保存目录。默认当前文件,文件夹images:param domain: website domain - 图片前缀域名"""if domain is not None:src = domain + srcpic = requests.get(src, timeout=20)# 去掉链接后面的参数src = src.split('?')[0]filepath = filedir + filename + src[-4:]if pic.status_code == 200:with open(filepath, 'wb') as f:f.write(pic.content)return filepath# 获取当前项目根路径
class JarProjectPath:@staticmethoddef project_root_path(project_name=None):"""获取当前项目根路径:param project_name::return: 根路径"""PROJECT_NAME = 'py' if project_name is None else project_nameproject_path = os.path.abspath(os.path.dirname(__file__))root_path = project_path[:project_path.find("{}\\".format(PROJECT_NAME)) + len("{}\\".format(PROJECT_NAME))]# print('当前项目名称:{}\r\n当前项目根路径:{}'.format(PROJECT_NAME, root_path))return root_path
!!! 获取项目根路径,记得把方法里的默认py换成你的项目名称~~PROJECT_NAME
其他说明
该py文件在 我的某一个文件夹sqc下,然后工具类又在另一个文件夹common下,这会使工具类不能直接在改文件中import util,
找不到这个util模块
PS C:\Users\dyjx\Desktop\py> & D:/Python/Python39/python.exe c:/Users/dyjx/Desktop/py/sqc/download_csdn_article.py
Traceback (most recent call last):File "c:\Users\dyjx\Desktop\py\sqc\download_csdn_article.py", line 6, in <module>import util
ModuleNotFoundError: No module named 'util'
你得需将这个文件夹加入搜索索引,这样之后。import util,才能找到
import sys, os
__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(__dir__)
sys.path.append(os.path.abspath(os.path.join(__dir__, './common')))import util
import logginglogging.basicConfig(filename = "out.txt",level=logging.DEBUG,format= "%(asctime)s %(levelname)s -- %(message)s")
所以,我又将上面这几行代码,又给整合到与两者文件夹同级的一个文件里module_path.py
再直接引用module_path.py,减少了每次复制上面的这几行代码,嘻嘻
from module_path import util, logging
保存后,好像 有一些小地方不对,再优化。比如 序号格式?第一行的标题
写完博客文章后,再给爬下来,保存在本地~ 哈阿哈相关推荐
- 忍不住跟着吐槽 —“当你辛辛苦苦写的博客文章被无情复制,成为了他的原创,你作何感想?”...
刚无意打开博客园乱扫一眼便看到48小时排行里面一篇文章 "当你辛辛苦苦写的博客文章被无情复制,成为了他的"原创",你作何感想?",看到这样的标题就一下子触碰到了 ...
- 写完博客发现无法用百度搜到?为什么百度搜索资源平台的“链接提交”无法提交链接?教你如何让百度快速收录自己的博客?
疑问 为什么美滋滋得写完博客之后,去百度上搜索却没有办法搜到呢?博客网站又不是亲手搭建的,也不需要购买域名,怎么就搜不到呢? 解答 每天都有无数人在网上发布帖子和博文,纵使百度的服务器再强大,也不能一 ...
- 上半年要写的博客文章27
这里写自定义目录标题 欢迎使用Markdown编辑器 新的改变 功能快捷键 合理的创建标题,有助于目录的生成 如何改变文本的样式 插入链接与图片 如何插入一段漂亮的代码片 生成一个适合你的列表 创建一 ...
- 上半年要写的博客文章29
这里写自定义目录标题 欢迎使用Markdown编辑器 新的改变 功能快捷键 合理的创建标题,有助于目录的生成 如何改变文本的样式 插入链接与图片 如何插入一段漂亮的代码片 生成一个适合你的列表 创建一 ...
- 上半年要写的博客文章21
这里写自定义目录标题 欢迎使用Markdown编辑器 新的改变 功能快捷键 合理的创建标题,有助于目录的生成 如何改变文本的样式 插入链接与图片 如何插入一段漂亮的代码片 生成一个适合你的列表 创建一 ...
- 上半年要写的博客文章30
这里写自定义目录标题 欢迎使用Markdown编辑器 新的改变 功能快捷键 合理的创建标题,有助于目录的生成 如何改变文本的样式 插入链接与图片 如何插入一段漂亮的代码片 生成一个适合你的列表 创建一 ...
- 当你辛辛苦苦写的博客文章被无情复制,成为了他的原创,你作何感想?
我一直都说我之所以开始写博客,是因为我是想把博客当成一个备忘录,同时也能分享给大家.我才开博1个月,还没有写几篇文章,我发现每篇文章都被很多网站转载了,有的署名或者是贴上我文章的地址作为来源地址. 对 ...
- 如何用更短时间写出高质量的博客文章经验分享
原文链接:http://www.techolics.com 真正有价值的是那些高质量内容的文章,而非转载和伪原创的内容.相信这是想做好一个以内容为主的博客博主和网站站长都不容质疑的观点.对于想发展独立 ...
- 如何在博客文章中使用表情符号?
本文由 大侠(AhcaoZhu)原创,转载请声明. 链接: https://blog.csdn.net/Ahcao2008 如何在博客文章中使用表情符号? 摘要: 收藏内容 How to 制作过程: ...
最新文章
- Git 常用操作(5)- git clone/git checkout -b/git diff/git push/git pull
- Windows 终端神器 MobaXterm,免费版可以在公司环境下使用
- PingCode与Jira 敏捷开发管理能力的对比
- VTK:直线用法实战
- Jenkins发布MVC应用程序
- Django 一些少用却很实用的orm查询方法
- 火狐浏览器 附件组件 Xpath 使用
- SolidWorks学习日记
- 华为查看mpls的命令_华为BGP基本命令
- ios定位权限plist_iOS(定位一)后台定位和前台定位权限设置
- php 如何拉取百度统计,如何添加百度统计工具?-MetInfo帮助中心
- idea 的Igonre 设置
- 基于FPGA的UART串口发送模块设计
- 狂野飙车显示无法连接服务器,狂野飙车(极速版)无法连接服务器是什么原因...
- mbk文件导入到oracle,linux下启动oracle
- 数位板使用技巧_保护您的眼睛技巧,以帮助防止数位眼疲劳
- python视频网站分类_科学网—爬取网站视频简单方法之一:python的you-get模块使用方法 - 周朝宪的博文...
- 丰田将在所有销售店安装充电设备丰田章男社长“建立共享基础设施”
- 编写程序,实现判断用户输入的数是正书还是负数的功能。
- 技嘉B560M VCCIO2电压设计缺陷