前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用Python爬取文章,并转PDF格式电子书

用Python爬取文章,并转PDF格式电子书

作者头像
松鼠爱吃饼干
发布2022-05-16 15:37:58
4210
发布2022-05-16 15:37:58
举报
文章被收录于专栏:Python分享Python分享

前言

前段时间,我在某个姓B的发了个视频,就是采集了自己的文章,转制成PDF格式的教程,CSDN居然给我举报了!!! 现在我来写一篇获取自己的文章,然后转制成PDF格式的电子式,看看能不能发出去

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

获取文章内容代码

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

代码实现

请求数据

代码语言:javascript
复制
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 表示请求成功

解析数据, 提取内容

代码语言:javascript
复制
for 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

保存数据

代码语言:javascript
复制
html_path = 'html\\' + title +'.html'
with open(html_path, mode='w', encoding=' utf-8') as f:
    f.write(article_content)
print(title,'保存成功')

转制为pdf文件

代码语言:javascript
复制
    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,'保存成功')
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-04-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 松鼠爱吃饼干 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
    • 获取文章内容代码
    • 代码实现
      • 请求数据
        • 解析数据, 提取内容
          • 保存数据
            • 转制为pdf文件
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档