首頁  >  文章  >  後端開發  >  python如何匯出微信公眾號文章

python如何匯出微信公眾號文章

coldplay.xixi
coldplay.xixi轉載
2020-08-29 16:34:183008瀏覽

python如何匯出微信公眾號文章

相關學習推薦:python教學

1.安裝wkhtmltopdf

#下載網址:https://wkhtmltopdf.org/downloads.html 

我測試用的是windows的,下載安裝後結果如下

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>
    <h2 style="text-align: center;font-weight: 400;">{title}</h2>
    {content_info[&#39;content_html&#39;]}
    </body>
    </html>
    &#39;&#39;&#39;
    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(&#39;%Y%m%d%H%M%S&#39;) + &#39;.pdf&#39;
        pdfkit.from_string(html, targetPath + os.path.sep + filename)



if __name__ == &#39;__main__&#39;:
    # 此处为要爬取公众号的名称

    url2pdf("https://mp.weixin.qq.com/s/wwT5n2JwEEAkrrmOhedziw", "HBase的系统架构全视角解读","G:/test/hbase文档.pdf" )
    # gzh_name = &#39;&#39;
    # # 如果不存在目标文件夹就进行创建
    # if not os.path.exists(targetPath):
    #     os.makedirs(targetPath)
    # # 将该公众号最近10篇文章信息以字典形式返回
    # data = ws_api.get_gzh_article_by_history(gzh_name)
    # article_list = data[&#39;article&#39;]
    # for article in article_list:
    #     url = article[&#39;content_url&#39;]
    #     title = article[&#39;title&#39;]
    #     url2pdf(url, title, targetPath)

相關學習推薦:微信小程式教學

以上是python如何匯出微信公眾號文章的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除