本文的文字及圖片來源於網絡,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理。
作者: 數據分析實戰
PS:如有需要Python學習資料的小伙伴可以加點擊下方鏈接自行獲取
http://note.youdao.com/noteshare?id=3054cce4add8a909e784ad934f956cef
主要功能
-
如何簡單爬蟲微信公眾號
-
獲取信息:標題、摘要、封面、文章地址
-
自動批量下載公眾號內的視頻
一、獲取公眾號信息:標題、摘要、封面、文章URL
操作步驟:
1、先自己申請一個公眾號 2、登錄自己的賬號,新建文章圖文,點擊超鏈接
代碼
1 import re 2 3 import requests 4 import jsonpath 5 import json 6 7 headers = { 8 "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36", 9 "Host": "mp.weixin.qq.com", 10 "Referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=10&isMul=1&isNew=1&lang=zh_CN&token=1862390040", 11 "Cookie": "自己獲取信息時的cookie" 12 } 13 14 def getInfo(): 15 for i in range(80): 16 # token random 需要要自己的 begin:參數傳入 17 url = "https://mp.weixin.qq.com/cgi-bin/appmsg?token=1904193044&lang=zh_CN&f=json&ajax=1&random=0.9468236563826882&action=list_ex&begin={}&count=5&query=&fakeid=MzI4MzkzMTc3OA%3D%3D&type=9".format(str(i * 5)) 18 19 response = requests.get(url, headers = headers) 20 21 jsonRes = response.json() 22 23 24 titleList = jsonpath.jsonpath(jsonRes, "$..title") 25 coverList = jsonpath.jsonpath(jsonRes, "$..cover") 26 urlList = jsonpath.jsonpath(jsonRes, "$..link") 27 28 # 遍歷 構造可存儲字符串 29 for index in range(len(titleList)): 30 title = titleList[index] 31 cover = coverList[index] 32 url = urlList[index] 33 34 scvStr = "%s,%s, %s,\n" % (title, cover, url) 35 with open("info.csv", "a+", encoding="gbk", newline='') as f: 36 f.write(scvStr)
獲取結果(成功):
二、獲取文章內視頻:實現批量下載
通過對單篇視頻文章分析,我找到了這個鏈接:
通過網頁打開發現,是視頻的網頁下載鏈接:
哎,好像有點意思了,找到了視頻的網頁純下載鏈接,那就開始吧。
發現鏈接里的有一個關鍵參數vid 不知道哪來的? 和獲取到的其他信息也沒有關系,那就只能硬來了。
通過對單文章的url請求信息里發現了這個參數,然后進行獲取。
1 response = requests.get(url_wxv, headers=headers) 2 3 # 我用的是正則,也可以使用xpath 4 jsonRes = response.text # 匹配:wxv_1105179750743556096 5 dirRe = r"wxv_.{19}" 6 result = re.search(dirRe, jsonRes) 7 8 wxv = result.group(0) 9 print(wxv)
視頻下載:
1 def getVideo(video_title, url_wxv): 2 video_path = './videoFiles/' + video_title + ".mp4" 3 4 # 頁面可下載形式 5 video_url_temp = "https://mp.weixin.qq.com/mp/videoplayer?action=get_mp_video_play_url&preview=0&__biz=MzI4MzkzMTc3OA==&mid=2247488495&idx=4&vid=" + wxv 6 response = requests.get(video_url_temp, headers=headers) 7 content = response.content.decode() 8 content = json.loads(content) 9 url_info = content.get("url_info") 10 video_url2 = url_info[0].get("url") 11 print(video_url2) 12 13 # 請求要下載的url地址 14 html = requests.get(video_url2) 15 # content返回的是bytes型也就是二進制的數據。 16 html = html.content 17 with open(video_path, 'wb') as f: 18 f.write(html)
那么所有信息就都完成了,進行code組裝。
a、獲取公眾號信息
b、篩選單篇文章信息
c、獲取vid信息
d、拼接視頻頁面下載URL
e、下載視頻,保存
代碼實驗結果: