亞寵展、全球寵物產業風向標——亞洲寵物展覽會深度解析
709
2022-05-30
今天要抓取的是虎牙頻道的直播頁,本篇博客的學習重點,依舊是多線程爬蟲。
目標數據分析
本次要采集的數據列表呈現如下,其中數據在切換時,來自于服務器接口,故本案例為面向接口的多線程爬蟲。
接口 API 如下所示:
https://www.huya.com/cache.php?m=LiveList&do=getLiveListByPage&tagAll=0&callback=getLiveListJsonpCallback&page=2 https://www.huya.com/cache.php?m=LiveList&do=getLiveListByPage&tagAll=0&callback=getLiveListJsonpCallback&page=3
接口請求方式為:GET
服務器數據返回格式為:JSON
其中參數說明如下:
m:猜測為頻道的意思;
do:接口名稱;
tagAll:標簽名;
callback:回調函數;
page:頁碼。
測試接口,發現除 callback 參數可以不傳遞以外,其余參數必須傳遞。
當 page 超出頁碼之后,數據返回內容為:
{ "status": 200, "message": "", "data": { "page": 230, "pageSize": 120, "totalPage": 228, "totalCount": 0, "datas": [], "time": 1630141551 } }
基于上述代碼,可通過第一次訪問接口,獲取到 totalPage,然后在生成所有待抓取的鏈接。
編碼時間
本案例代碼編寫難度中等,核心在服務器返回數據部分,由于數據是異步加載,故返回的數據為下圖所示,當 callback 參數存在值時,返回的數據也被參數值 getLiveListJsonpCallback 包裹,去除該參數值即為圖二所示。
圖一
圖二
如果繼續攜帶 callback 參數,可使用如下代碼對返回數據進行修改,即刪除相應內容頭部多余數據,并且刪除最后一個括號數據。
res.encoding = 'utf-8' text = res.text text = text.replace('getLiveListJsonpCallback(', '') text = text[:-1]
完整虎牙直播 JSON 數據爬取
本案例與上一案例實現邏輯基本一致,僅在數據請求與解析出體現出細微差別,大家在學習時,可以對比學習。
最后獲取到的數據,直接存儲為 JSON 格式數據,可自行更改其它格式。
import threading import requests import random class Common: def __init__(self): pass def get_headers(self): uas = [ "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)", "其余內容" ] ua = random.choice(uas) headers = { "user-agent": ua, "referer": "https://www.baidu.com" } return headers def run(index, url, semaphore, headers): semaphore.acquire() # 加鎖 res = requests.get(url, headers=headers, timeout=5) res.encoding = 'utf-8' text = res.text text = text.replace('getLiveListJsonpCallback(', '') text = text[:-1] # print(text) # json_data = json.loads(text) # print(json_data) save(index,text) semaphore.release() # 釋放 def save(index, text): with open(f"./虎牙/{index}.json", "w", encoding="utf-8") as f: f.write(f"{text}") print("該URL地址數據寫入完畢") if __name__ == '__main__': # 獲取總頁碼 first_url = 'https://www.huya.com/cache.php?m=LiveList&do=getLiveListByPage&tagAll=0&callback=&page=1' c = Common() res = requests.get(url=first_url, headers=c.get_headers()) data = res.json() if data['status'] == 200: total_page = data['data']['totalPage'] url_format = 'https://www.huya.com/cache.php?m=LiveList&do=getLiveListByPage&tagAll=0&callback=&page={}' # 拼接URL,全局共享變量 urls = [url_format.format(i) for i in range(1, total_page)] # 最多允許5個線程同時運行 semaphore = threading.BoundedSemaphore(5) for i, url in enumerate(urls): t = threading.Thread(target=run, args=(i, url, semaphore, c.get_headers())) t.start() while threading.active_count() != 1: pass else: print('所有線程運行完畢')
Python 數據挖掘 視頻直播
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。