溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python導出微信公眾號文章的方法

發(fā)布時間:2020-08-31 09:42:53 來源:億速云 閱讀:291 作者:小新 欄目:編程語言

這篇文章將為大家詳細講解有關python導出微信公眾號文章的方法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

1.安裝wkhtmltopdf

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

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

python導出微信公眾號文章的方法

2 編寫python 代碼導出微信公眾號文章

不能直接使用wkhtmltopdf 導出微信公眾號文章,導出的文章會缺失圖片,所以需要使用 wechatsogou 將微信公眾號文章頁面抓取,之后將html文本轉化為pdf

pip install wechatsogou --upgrade

pip install pdfkit

踩坑?。?!,看了很多人的代碼,都是一個模板,大家都是抄來抄去,結果還是運行不了,可能是因為依賴包更新的原因,也可能是因為我本地沒有配置wkhtmltopdf 的環(huán)境變量

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的系統(tǒng)架構全視角解讀","G:/test/hbase文檔.pdf" )
    # gzh_name = ''
    # # 如果不存在目標文件夾就進行創(chuàng)建
    # 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導出微信公眾號文章的方法就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI