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['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 = https://www.cnblogs.com/pythonzhilian/p/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黑洞網,博客園同步更新
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/10161.html
標籤:Python
上一篇:11_IO多路復用
