打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python爬虫案例:下载文章数据,转制成PDF格式
userphoto

2022.05.03 新疆

关注

wkhtmltopdf [软件],这个是必学准备好的,不然这个案例是实现不出来的

获取文章内容代码

  1. 发送请求, 对于url地址发送请求
  2. 解析数据, 提取内容
  3. 保存数据, 先保存成html文件
  4. 再把html文件转成PDF

代码实现

# 请求数据import requests # 数据请求模块url = f'https://blog.csdn.net/fei347795790/article/list/1' # 确定请求网址# headers 请求头, 主要用于伪装python, 防止程序被服务器识别出来headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36'}# 用requests模块里面get方式发送请求response = requests.get(url=url, headers=headers)print(response.text)# <Response [200]> 响应对象 200 表示请求成功# 解析数据, 提取内容# 更多资源、源码、解答可加:832157862for index in href: html_data = requests.get(url=index, headers=headers).text selector_1 = parsel.Selector(html_data) title = selector_1.css('#articleContentId::text').get() content = selector_1.css('#content_views').get() article_content = html_str.format(article=content) print(title) print(article_content) break# 保存数据html_path = 'html\\' + title +'.html'with open(html_path, mode='w', encoding=' utf-8') as f: f.write(article_content)print(title,'保存成功')

image.png

image.png

转制为pdf文件

    html_path = 'html\\ + title + '.html'    pdf_path = 'pdf\\' + title + '.pdf'    with open(html_path, mode='w', encoding='utf-8') as f:        f.write(article_content)    config = pdfkit.configuration(wkhtmltopdf=r'C:\01-Software-installation\wkhtmltopdf\bin\wkhtmltopdf.exe')    ppdfkit.from_file(html_path,pdf_path,configuration=config)    print(title,'保存成功')# 更多资源、源码、解答可加:832157862

image.png

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python爬虫实现的微信公众号文章下载器
python pdfkit生成PDF
爬虫实战【3】Python
为了学爬虫,我用三步爬取了大佬崔庆才爬虫相关文章,并保持为pdf学习
Python爬虫新手入门教学(十六):爬取网站音乐素材
wkhtmltopdf:wkhtmltopdf(将html转换成pdf的利器)简介、安装、使用方法详细攻略
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服