溫馨提示×

溫馨提示×

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

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

如何爬取微信公眾號文章并保存為PDF文件

發(fā)布時間:2021-01-30 11:03:03 來源:億速云 閱讀:322 作者:小新 欄目:移動開發(fā)

小編給大家分享一下如何爬取微信公眾號文章并保存為PDF文件,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

爬取微信公眾號文章(使用wechatsogou)

1.安裝

pip install wechatsogou --upgrade

wechatsogou是一個基于搜狗微信搜索的微信公眾號爬蟲接口

2.使用方法

使用方法如下所示

import wechatsogou
# captcha_break_time為驗證碼輸入錯誤的重試次數(shù),默認為1
ws_api = wechatsogou.WechatSogouAPI(captcha_break_time=3)
# 公眾號名稱
gzh_name = ''
# 將該公眾號最近10篇文章信息以字典形式返回
data = ws_api.get_gzh_article_by_history(gzh_name)

data數(shù)據(jù)結(jié)構(gòu):

{
    'gzh': {
        'wechat_name': '',  # 名稱
        'wechat_id': '',  # 微信id
        'introduction': '',  # 簡介
        'authentication': '',  # 認證
        'headimage': ''  # 頭像
    },
    'article': [
        {
            'send_id': int,  # 群發(fā)id,注意不唯一,因為同一次群發(fā)多個消息,而群發(fā)id一致
            'datetime': int,  # 群發(fā)datatime 10位時間戳
            'type': '',  # 消息類型,均是49(在手機端歷史消息頁有其他類型,網(wǎng)頁端最近10條消息頁只有49),表示圖文
            'main': int,  # 是否是一次群發(fā)的第一次消息 1 or 0
            'title': '',  # 文章標(biāo)題
            'abstract': '',  # 摘要
            'fileid': int,  #
            'content_url': '',  # 文章鏈接
            'source_url': '',  # 閱讀原文的鏈接
            'cover': '',  # 封面圖
            'author': '',  # 作者
            'copyright_stat': int,  # 文章類型,例如:原創(chuàng)啊
        },
        ...
    ]
}

這里需要得到兩個信息:文章標(biāo)題,文章url。

得到文章url以后,就可以根據(jù)url將html頁面轉(zhuǎn)換成pdf文件了。

生成PDF文件

1.安裝wkhtmltopdf

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

2.安裝pdfkit

pip install pdfkit

3.使用方法

import pdfkit
# 根據(jù)url生成pdf
pdfkit.from_url('http://baidu.com','out.pdf')
# 根據(jù)html文件生成pdf
pdfkit.from_file('test.html','out.pdf')
# 根據(jù)html代碼生成pdf
pdfkit.from_string('Hello!','out.pdf')

如果直接用上面得到的文章url去生成pdf,會出現(xiàn)pdf文件不顯示文章圖片的問題。

解決辦法:

# 該方法根據(jù)文章url對html進行處理,使圖片顯示
content_info = ws_api.get_article_content(url)
# 得到html代碼(代碼不完整,需要加入head、body等標(biāo)簽)
html_code = content_info['content_html']

然后根據(jù)html_code構(gòu)造完整的html代碼,調(diào)用pdfkit.from_string()方法生成pdf文件,這時候會發(fā)現(xiàn)文章中的圖片在pdf文件中顯示出來了。

完整代碼

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: 存儲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:
        pdfkit.from_string(html, targetPath + os.path.sep + f'{title}.pdf')
    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__':
    # 此處為要爬取公眾號的名稱
    gzh_name = ''
    targetPath = os.getcwd() + os.path.sep + gzh_name
    # 如果不存在目標(biāo)文件夾就進行創(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)

看完了這篇文章,相信你對“如何爬取微信公眾號文章并保存為PDF文件”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

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

AI