1. 程式人生 > 程式設計 >python如何匯出微信公眾號文章方法詳解

python如何匯出微信公眾號文章方法詳解

python如何匯出微信公眾號文章方法詳解

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'''
{title}
 {content_info['content_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,targetPath)

到此這篇關於python如何匯出微信公眾號文章方法詳解的文章就介紹到這了,更多相關python匯出微信公眾號文章內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!