如何使用 Python 爬取微信公衆號文章

我比較喜歡看公衆號,有時遇到一個感興趣的公衆號時,都會感受相逢恨晚,想一口氣看完全部歷史文章。可是微信的閱讀體驗挺很差的,看歷史文章得一頁頁的日後翻,下一次再看時還得重複操做,非常麻煩。html

因而便想着能不能把某個公衆號全部的文章都保存下來,這樣就很方便本身閱讀歷史文章了。python

話很少說,下面我就介紹如何使用 Python 爬取微信公衆號全部文章的。web

主要有如下步驟:json

1 使用 Fiddler 抓取公衆號接口數據微信

2 使用 Python 腳本獲取公衆號全部歷史文章數據網絡

3 保存歷史文章數據結構

Fiddler 抓包

Fiddler 是一款抓包工具,能夠監聽網絡通信數據,開發測試過程當中很是有用,這裏很少作介紹。沒有使用過的能夠查看這篇文章,很容易上手。app

https://blog.csdn.net/jingjingshizhu/article/details/80566191工具

接下來,使用微信桌面客戶端,打開某個公衆號的歷史文章,這裏以個人公衆號舉例,以下圖。測試

若是你的 fiddler 配置好了的話,可以看到以下圖的數據。

圖中包含抓取的 url、一些重要的參數和咱們想要的數據。

這些參數中,offset 控制着翻頁,其餘參數在每一頁中都是固定不變的。

接口返回的數據結構以下圖,其中 can_msg_continue 字段控制着可否翻頁,1 表示還有下一頁,0 表示沒有已是最後一頁了。next_offset 字段就是下一次請求的 offset 參數。

構造請求,獲取數據

接下來咱們的目標就是根據 url 和一些參數,構建請求,獲取標題、文章 url 和日期等數據,保存數據。

保存數據一種是使用 pdfkit 將 文章 url 保存爲 pdf 文件;另外一種是先保存 html 文件,而後將 html 製做成 chm 文件。

1 將 文章 url 保存爲 pdf 文件,關鍵代碼以下:

def parse(index, biz, uin, key):
    # url前綴
    url = "https://..."

    # 請求頭
    headers = {
        "User-Agent""Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 "
                      "Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.901.400 "
                      "QQBrowser/9.0.2524.400",
    }

    proxies = {
        'https'None,
        'http'None,
    }

    # 重要參數
    param = {
        'action''getmsg',
        '__biz': biz,
        'f''json',
        'offset': index * 10,
        'count''10',
        'is_ok''1',
        'scene''124',
        'uin': uin,
        'key': key,
        'wxtoken''',
        'x5''0',
    }

    # 發送請求,獲取響應
    response = requests.get(url, headers=headers, params=param, proxies=proxies)
    response_dict = response.json()

    print(response_dict)

    next_offset = response_dict['next_offset']
    can_msg_continue = response_dict['can_msg_continue']

    general_msg_list = response_dict['general_msg_list']
    data_list = json.loads(general_msg_list)['list']

    # print(data_list)

    for data in data_list:
        try:
            # 文章發佈時間
            datetime = data['comm_msg_info']['datetime']
            date = time.strftime('%Y-%m-%d', time.localtime(datetime))

            msg_info = data['app_msg_ext_info']

            # 文章標題
            title = msg_info['title']

            # 文章連接
            url = msg_info['content_url']

            # 本身定義存儲路徑(絕對路徑)
            pdfkit.from_url(url, 'C:/Users/admin/Desktop/wechat_to_pdf/' + date + title + '.pdf')

            print(title + date + '成功')

        except:
            print("不是圖文消息")

    if can_msg_continue == 1:
        return True
    else:
        print('爬取完畢')
        return False

2 保存 html 文件,關鍵代碼以下

def parse(index, biz, uin, key):

    # url前綴
    url = "https://..."

    # 請求頭
    headers = {
        "User-Agent""Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 "
                      "Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.901.400 "
                      "QQBrowser/9.0.2524.400",
    }

    proxies = {
        'https'None,
        'http'None,
    }

    # 重要參數
    param = {
        'action''getmsg',
        '__biz': biz,
        'f''json',
        'offset': index * 10,
        'count''10',
        'is_ok''1',
        'scene''124',
        'uin': uin,
        'key': key,
        'wxtoken''',
        'x5''0',
    }

    # 發送請求,獲取響應
    reponse = requests.get(url, headers=headers, params=param, proxies=proxies)
    reponse_dict = reponse.json()

    # print(reponse_dict)
    next_offset = reponse_dict['next_offset']
    can_msg_continue = reponse_dict['can_msg_continue']

    general_msg_list = reponse_dict['general_msg_list']
    data_list = json.loads(general_msg_list)['list']

    print(data_list)

    for data in data_list:
        try:
            datetime = data['comm_msg_info']['datetime']
            date = time.strftime('%Y-%m-%d', time.localtime(datetime))

            msg_info = data['app_msg_ext_info']

            # 標題
            title = msg_info['title']

            # 內容的url
            url = msg_info['content_url'].replace("\\""").replace("http""https")
            url = html.unescape(url)
            print(url)

            res = requests.get(url, headers=headers, proxies=proxies)
            with open('C:/Users/admin/Desktop/test/' + title + '.html''wb+'as f:
                f.write(res.content)

            print(title + date + '成功')

        except:
            print("不是圖文消息")

    if can_msg_continue == 1:
        return True
    else:
        print('所有獲取完畢')
        return False

保存文章

保存爲 pdf 文件,用到了 python 的第三方庫 pdfkit 和 wkhtmltopdf。

安裝 pdfkit:

pip install pdfkit

安裝 wkhtmltopdf:

下載地址:

https://wkhtmltopdf.org/downloads.html

安裝後將 wkhtmltopdf 目錄下的 bin 添加到環境變量中。

保存爲 chm 文件,能夠下載 Easy CHM ,使用這個軟件能夠將 html 製做成 chm,使用教程網上比較多。

下載地址:

http://www.etextwizard.com/cn/easychm.html

效果圖:

pdf 和 chm 對比

pdf 支持多終端,閱讀體驗好,可是有個大坑,就是微信文章保存的 pdf 沒有圖片,很影響閱讀體驗,暫未找到解決辦法。

chm 的好處是能夠創建索引,查看文章方便。一個公衆號製做成一個 chm 文件,管理方便。不會出現圖片不顯示問題。

因此推薦將爬取到的公衆號文章保存爲 chm 文件,方便閱讀。

須要完整代碼和文中相關軟件的朋友,後臺回覆關鍵詞 」公衆號文章「 獲取。

感謝關注

本文分享自微信公衆號 - 賈小昆(zywudev)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索