不知不觉,从开始写公众号文章到现在已有两年有余。有过寥寥无几阅读量的挫败,也有突然涨粉上百人的兴奋。
今天正好得空,就想将自己这两年多以来发出的公众号文章都整理一番,可是一个一个手动的去复制链接/标题以及时间信息实在太过麻烦。而且手动还可能出现错乱的情况。
做为一个软件开发兼python爱好者,手动那是不可能手动的。
既然,我们只是想获取自己公众号的文章信息,那为什么不使用网络请求request和cookie认证的方式呢?
于是,我实现了整个过程,经过测试可以成功的获取到的我自己的公众号文章的信息,简直就是最简单的爬虫嘛!
接下来,我们直接进入正题吧,首先将需要的python模块全部导入进来吧,若是没有安装requests模块,使用pip的方式安装一下就OK啦。
pip install reauests
# It imports the time module.
import time
# It imports the random module.
import random
# It imports the requests module.
import requests
from loguru import logger
由于公众号接口返回的时间参数都是时间戳,因此我们先开发一个时间戳转换函数transDateTime()。
def transDateTime(time_stamp=None):
"""
This function takes a time stamp and returns a string of the date and time in the format of "YYYY-MM-DD HH:MM:SS"
:param time_stamp: The time stamp you want to convert. If you don't provide one, the current time will be used
"""
if time_stamp is None:
logger.error('时间戳不能为空!')
return
else:
time_arr = time.localtime(time_stamp)
date_time = time.strftime("%Y-%m-%d %H:%M:%S", time_arr)
return date_time
在开始获取公众号文章的信息之前,我们需要获取到已登录的cookie信息/token值/以及分享文章时的fakeId,这些信息都可以在自己的文章链接和F12浏览器中可以获取到,这里不再赘述。
若是不知道如何获取的话可以留言或是公众号内发送消息,我看到后都会给解答。
下面我们创建一个函数getAllActicleList(),用来不断的发送request请求获取文章的返回信息。
def getAllActicleList(fake_id=None, token=None, total_num=None, cookie=None):
"""
This function takes a time stamp and returns a string of the date and time in the format of "YYYY-MM-DD HH:MM:SS"
:param time_stamp: The time stamp you want to convert. If you don't provide one, the current time will be used
:return: A string of the date and time in the format of "YYYY-MM-DD HH:MM:%S"
"""
if fake_id is None or token is None or total_num is None or cookie is None:
logger.error('网络请求参数皆不能为空!')
else:
index_url = "https://mp.weixin.qq.com/cgi-bin/appmsg"
headers = {
"Cookie": cookie,
"User-Agent": ""
}
data = {
"token": token,
"lang": "zh_CN",
"f": "json",
"ajax": "1",
"action": "list_ex",
"begin": "0",
"count": "5",
"query": "",
"fakeid": fake_id,
"type": "9",
}
list_all = []
for n_ in range(total_num):
data["begin"] = n_ * 5
time.sleep(random.randint(5, 12))
content_json = requests.get(index_url, headers=headers, params=data).json()
print(content_json)
for item in content_json["app_msg_list"]:
items = [item["title"], item["link"], item["cover"], transDateTime(item["create_time"]), item["digest"],
item["item_show_type"], transDateTime(item["update_time"]), ''.join(fake_id)]
print(items)
list_all.append(items)
logger.info('第{}页文章信息提取完成!'.format(n_))
logger.info('所有文章信息全部获取完成!')
if __name__ == '__main__':
cookie = "pgv_pvid=9057447067; fqm_pvqid=395435a5-f777-422b-98c9-95b04ec25b5d; ua_id=39FvIEnILeBLbxayAAAAAIgUbbtk3PCL_aL8F7GbDoQ=; wxuin=69813312865817; mm_lang=zh_CN; eas_sid=V1k6f699v8L1c9m1d7f6E5b2G5; RK=c4t0n6rBHH; ptcz=af6350b43aedaca6adb9ae25c82919191828e2f1b4b6cb847cf3a8bebcea7937; _clck=3078953842|1|f7b|0; tvfe_boss_uuid=7e9e190bc18dc488; ts_uid=4218420912; __root_domain_v=.weixin.qq.com; _qddaz=QD.504676987481682; uin=o1342929047; rewardsn=; wxtokenkey=777; wwapp.vid=; wwapp.cst=; wwapp.deviceid=; uuid=b64c2b3c199de94d92136498626d8d8c; rand_info=CAESIJMyV7yjUv/6bgxaYCj27D464fzyX830vFsS8oO7gG99; slave_bizuin=3078953842; data_bizuin=3276163951; bizuin=3078953842; data_ticket=gVPTYyNSO7hxyJjbog60srqEdp0Fi/S/J4fGZjalT8vMHTnQfOgdyUtyvM/QNQvu; slave_sid=Y3I1dGJuWXFoeHY2ZW01ZlpPZV9FTXIyMkhUb3l3QkNXTVJOa05qdGhwUWZIdGdodFJUS0lKOXNpYXBqNVNmSmpWV2VNYkpLR1hlYW01NUFBSDd2bWNtQVlvS0JkbGRPTEVGWUh1RXJ6dmt5am5acG42NnBaM2JoQXA4aWxlWmFmYXVqaGxNcTczdzA1YnNq; slave_user=gh_aab1550ed027; xid=85c2199d1dbf2bf27c2f2fc8f9d173f9"
getAllActicleList(fake_id='MzA3ODk1Mzg0Mg==', token='1459807521', total_num=100, cookie=cookie)
上述cookie信息可以从浏览器中按F12在接口API信息中获取到,以及fake_id/token等信息
也可以获取到。

感谢小伙伴们一直依赖对[Python 集中营]的支持,我们会一如既往发现更多的编程实例来回馈大家,欢迎在评论区留言讨论!