python爬取抖音直播数据评论
pip3 install websockets
主要用到的API有:
websockets.connect()
websockets.send()
websockets.recv()
server.py,用于搭建webscocket服务器,在本地8888端口启动,接收到消息后会在原消息前加上I got your message:再返回去。
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
message = "I got your message: {}".format(message)
await websocket.send(message)
asyncio.get_event_loop().run_until_complete(websockets.serve(echo, 'localhost', 8888))
asyncio.get_event_loop().run_forever()
#!/usr/bin/env python
import asyncio
import websockets
async def hello(uri):
async with websockets.connect(uri) as websocket:
await websocket.send("hello world")
print("< HELLO WORLD")
while True:
recv_text = await websocket.recv()
print("> {}".format(recv_text))
asyncio.get_event_loop().run_until_complete(hello('ws://localhost:8888'))
先执行server.py,然后执行client.py,client.py的输出结果如下:
< Hello world!
I got your message: Hello world!
2022-09-05 21:11:50