在寫爬蟲的時候,偶爾會碰到要爬取的網站或者app數據是通過websocket返回的,這時候,我們可以通過Python的 aiowebsocket這個庫來進行爬取,下面是一個簡單的示例代碼,獲取指定ws地址的數據並打印:
import asyncio
import logging
from aiowebsocket.converses import AioWebSocket
import json
'''
pip install aiowebsocket
'''
async def startup(uri):
async with AioWebSocket(uri) as aws:
converse = aws.manipulator
# 客戶端給服務端發送消息,這個 wsid 參數是自己通過分析抓包獲取到的心跳參數
await converse.send('{"wsid":1}')
num=0
while True:
mes = await converse.receive()
#這裏我是採用的累計的5的倍數的時候,向服務端發送一次心跳,保持連接
num+=1
if num%5==0:
await converse.send('{"wsid":1}')
#如果獲取到數據,就打印出來,我這裏獲取到的因爲是json字符串,所以把它轉換成了json打印
if mes:
msg=json.loads(str(mes, encoding="utf-8"))
print(msg)
if __name__ == '__main__':
#要連接的websocket地址
remote = 'wss://app.qkvoice.com/websocket?wsid=8e033c14-c329-4f23-87c2-dab8c17d3a0e'
try:
asyncio.get_event_loop().run_until_complete(startup(remote))
except KeyboardInterrupt as exc:
logging.info('Quit.')