python如何导出微信公众号文章


本文摘自php中文网,作者coldplay.xixi,侵删。

相关学习推荐:python教程

1.安装wkhtmltopdf

下载地址:https://wkhtmltopdf.org/downloads.html

我测试用的是windows的,下载安装后结果如下

2 编写python 代码导出微信公众号文章

不能直接使用wkhtmltopdf 导出微信公众号文章,导出的文章会缺失图片,所以需要使用 wechatsogou 将微信公众号文章页面抓取,之后将html文本转化为pdf

pip install wechatsogou --upgrade

pip install pdfkit

踩坑!!!,看了很多人的代码,都是一个模板,大家都是抄来抄去,结果还是运行不了,可能是因为依赖包更新的原因,也可能是因为我本地没有配置wkhtmltopdf 的环境变量

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

import os

import pdfkit

import datetime

import wechatsogou

# 初始化API

 

ws_api = wechatsogou.WechatSogouAPI(captcha_break_time=3)

def url2pdf(url, title, targetPath):

    '''

    使用pdfkit生成pdf文件

    :param url: 文章url

    :param title: 文章标题

    :param targetPath: 存储pdf文件的路径

    '''

    try:

        content_info = ws_api.get_article_content(url)

    except:

        return False

    # 处理后的html

    html = f'''

    <!DOCTYPE html>

    <html lang="en">

    <head>

        <meta charset="UTF-8">

        <title>{title}</title>

    </head>

    <body>

    <h2 style="text-align: center;font-weight: 400;">{title}</h2>

    {content_info['content_html']}

    </body>

    </html>

    '''

    try:

        path_wk="E:/softwareAPP/wkhtmltopdf/bin/wkhtmltopdf.exe";

        config=pdfkit.configuration(wkhtmltopdf=path_wk)

        pdfkit.from_string(input=html, output_path=targetPath,configuration=config)

 

    except:

        # 部分文章标题含特殊字符,不能作为文件名

        filename = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.pdf'

        pdfkit.from_string(html, targetPath + os.path.sep + filename)

 

 

 

if __name__ == '__main__':

    # 此处为要爬取公众号的名称

 

    url2pdf("https://mp.weixin.qq.com/s/wwT5n2JwEEAkrrmOhedziw", "HBase的系统架构全视角解读","G:/test/hbase文档.pdf" )

    # gzh_name = ''

    # # 如果不存在目标文件夹就进行创建

    # if not os.path.exists(targetPath):

    #     os.makedirs(targetPath)

    # # 将该公众号最近10篇文章信息以字典形式返回

    # data = ws_api.get_gzh_article_by_history(gzh_name)

    # article_list = data['article']

    # for article in article_list:

    #     url = article['content_url']

    #     title = article['title']

    #     url2pdf(url, title, targetPath)

相关学习推荐:微信小程序教程

以上就是python如何导出微信公众号文章的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

关于Python下如何实现rsa的加密解密以及签名与验证功能的实例分析

Python如何获取列表长度?(代码示例)

Python扩展内置类型的实现方法分析

Python如何实现从 str 和 list的互相转化

Python堆排序算法实例代码

Python中字符串可以遍历吗

Python怎么统计文件中大写字母的个数?

Python采用什么开源协议

Python怎么念

怎么用Python打开文件

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...