【相關(guān)學(xué)習(xí)推薦:python教程】
1.安裝wkhtmltopdf
下載地址:https://wkhtmltopdf.org/downloads.html
我測(cè)試用的是windows的,下載安裝后結(jié)果如下
2 編寫(xiě)python 代碼導(dǎo)出微信公眾號(hào)文章
不能直接使用wkhtmltopdf 導(dǎo)出微信公眾號(hào)文章,導(dǎo)出的文章會(huì)缺失圖片,所以需要使用 wechatsogou 將微信公眾號(hào)文章頁(yè)面抓取,之后將html文本轉(zhuǎn)化為pdf
pip install wechatsogou –upgrade
pip install pdfkit
踩坑!??!,看了很多人的代碼,都是一個(gè)模板,大家都是抄來(lái)抄去,結(jié)果還是運(yùn)行不了,可能是因?yàn)橐蕾?lài)包更新的原因,也可能是因?yàn)槲冶镜貨](méi)有配置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: 文章標(biāo)題 :param targetPath: 存儲(chǔ)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: # 部分文章標(biāo)題含特殊字符,不能作為文件名 filename = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.pdf' pdfkit.from_string(html, targetPath + os.path.sep + filename) if __name__ == '__main__': # 此處為要爬取公眾號(hào)的名稱(chēng) url2pdf("https://mp.weixin.qq.com/s/wwT5n2JwEEAkrrmOhedziw", "HBase的系統(tǒng)架構(gòu)全視角解讀","G:/test/hbase文檔.pdf" ) # gzh_name = '' # # 如果不存在目標(biāo)文件夾就進(jìn)行創(chuàng)建 # if not os.path.exists(targetPath): # os.makedirs(targetPath) # # 將該公眾號(hào)最近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)
相關(guān)學(xué)習(xí)推薦:微信小程序教程