python导出微信公众号文章的方法

这篇文章将为大家详细讲解有关python导出微信公众号文章的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

创新互联主营湖北网站建设的网络公司,主营网站建设方案,成都app软件开发公司,湖北h5成都微信小程序搭建,湖北网站营销推广欢迎湖北等地区企业咨询

1.安装wkhtmltopdf

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

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

python导出微信公众号文章的方法

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

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

pip install wechatsogou --upgrade

pip install pdfkit

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

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>
    <h3 style="text-align: center;font-weight: 400;">{title}</h3>
    {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导出微信公众号文章的方法
地址分享:https://www.cdcxhl.com/article0/ishhoo.html

成都网站建设公司_创新互联,为您提供品牌网站建设网站维护Google手机网站建设App设计移动网站建设

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

微信小程序开发