溫馨提示×

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

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

用python爬取公眾號(hào)的方法

發(fā)布時(shí)間:2020-07-09 11:23:57 來源:億速云 閱讀:506 作者:清晨 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)用python爬取公眾號(hào)的方法,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

用python爬取公眾號(hào)文章的方法是:1、使用Fiddler抓取公眾號(hào)接口數(shù)據(jù);2、使用Python腳本獲取公眾號(hào)所有歷史文章數(shù)據(jù);3、利用pdfkit庫保存歷史文章。

用python爬取公眾號(hào)的方法

我比較喜歡看公眾號(hào),有時(shí)遇到一個(gè)感興趣的公眾號(hào)時(shí),都會(huì)感覺相逢恨晚,想一口氣看完所有歷史文章。但是微信的閱讀體驗(yàn)挺不好的,看歷史文章得一頁頁的往后翻,下一次再看時(shí)還得重復(fù)操作,很是麻煩。

于是便想著能不能把某個(gè)公眾號(hào)所有的文章都保存下來,這樣就很方便自己閱讀歷史文章了。

話不多說,下面我就介紹如何使用 Python 爬取微信公眾號(hào)所有文章的。

主要有以下步驟:

1 使用 Fiddler 抓取公眾號(hào)接口數(shù)據(jù)

2 使用 Python 腳本獲取公眾號(hào)所有歷史文章數(shù)據(jù)

3 保存歷史文章

Fiddler 抓包

Fiddler 是一款抓包工具,可以監(jiān)聽網(wǎng)絡(luò)通訊數(shù)據(jù),開發(fā)測(cè)試過程中非常有用,這里不多做介紹。沒有使用過的可以查看這篇文章,很容易上手。

blog.csdn.net/jingjings

接下來,使用微信桌面客戶端,打開某個(gè)公眾號(hào)的歷史文章,這里以我的公眾號(hào)舉例,如下圖。

如果你的 fiddler 配置好了的話,能夠看到如下圖的數(shù)據(jù)。

圖中包含抓取的 url、一些重要的參數(shù)和我們想要的數(shù)據(jù)。

這些參數(shù)中,offset 控制著翻頁,其他參數(shù)在每一頁中都是固定不變的。

接口返回的數(shù)據(jù)結(jié)構(gòu)如下圖,其中 can_msg_continue 字段控制著能否翻頁,1 表示還有下一頁,0 表示沒有已經(jīng)是最后一頁了。 next_offset 字段就是下一次請(qǐng)求的 offset 參數(shù)。

構(gòu)造請(qǐng)求,獲取數(shù)據(jù)

接下來我們的目標(biāo)就是根據(jù) url 和一些參數(shù),構(gòu)建請(qǐng)求,獲取標(biāo)題、文章 url 和日期等數(shù)據(jù),保存數(shù)據(jù)。

保存數(shù)據(jù)一種是使用 pdfkit 將 文章 url 保存為 pdf 文件;另一種是先保存 html 文件,然后將 html 制作成 chm 文件。

1 將 文章 url 保存為 pdf 文件,關(guān)鍵代碼如下:

def parse(index, biz, uin, key):
    # url前綴
    url = "https://mp.weixin.qq.com/mp/profile_ext"
    # 請(qǐng)求頭
    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,
    }
    # 重要參數(shù)
    param = {
        'action': 'getmsg',
        '__biz': biz,
        'f': 'json',
        'offset': index * 10,
        'count': '10',
        'is_ok': '1',
        'scene': '124',
        'uin': uin,
        'key': key,
        'wxtoken': '',
        'x5': '0',
    }
    # 發(fā)送請(qǐng)求,獲取響應(yīng)
    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:
            # 文章發(fā)布時(shí)間
            datetime = data['comm_msg_info']['datetime']
            date = time.strftime('%Y-%m-%d', time.localtime(datetime))
            msg_info = data['app_msg_ext_info']
            # 文章標(biāo)題
            title = msg_info['title']
            # 文章鏈接
            url = msg_info['content_url']
            # 自己定義存儲(chǔ)路徑(絕對(duì)路徑)
            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 文件,關(guān)鍵代碼如下

def parse(index, biz, uin, key):    # url前綴    url = "https://mp.weixin.qq.com/mp/profile_ext"    # 請(qǐng)求頭    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,    }    # 重要參數(shù)    param = {        'action': 'getmsg',        '__biz': biz,        'f': 'json',        'offset': index * 10,        'count': '10',        'is_ok': '1',        'scene': '124',        'uin': uin,        'key': key,        'wxtoken': '',        'x5': '0',    }    # 發(fā)送請(qǐng)求,獲取響應(yīng)    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']            # 標(biāo)題            title = msg_info['title']            # 內(nèi)容的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:

下載地址:

wkhtmltopdf.org/downloa

安裝后將 wkhtmltopdf 目錄下的 bin 添加到環(huán)境變量中。

保存為 chm 文件,可以下載 Easy CHM ,使用這個(gè)軟件可以將 html 制作成 chm,使用教程網(wǎng)上比較多。

下載地址:

etextwizard.com/cn/easy

效果圖:

pdf 和 chm 對(duì)比

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

chm 的好處是可以建立索引,查看文章方便。一個(gè)公眾號(hào)制作成一個(gè) chm 文件,管理方便。不會(huì)出現(xiàn)圖片不顯示問題。

所以推薦將爬取到的公眾號(hào)文章保存為 chm 文件,方便閱讀。

關(guān)于用python爬取公眾號(hào)的方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

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

AI