店播爬取Python脚本

demo.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/usr/bin/python3
  2. #coding=utf-8
  3. #-*- coding: UTF-8 -*
  4. import random
  5. import websocket
  6. from barrage import MessageDecode
  7. try:
  8. import thread
  9. except ImportError:
  10. import _thread as thread
  11. import time
  12. def get_page_id():
  13. charset = "bjectSymhasOwnProp-0123456789ABCDEFGHIJKLMNQRTUVWXYZ_dfgiklquvxz"
  14. page_id = ''
  15. for _ in range(0, 16):
  16. page_id += random.choice(charset)
  17. page_id += "_"
  18. page_id += str(int(time.time() * 1000))
  19. return page_id
  20. def on_message(ws, message):
  21. data = [m for m in message]
  22. message = MessageDecode(data)
  23. if message.decode():
  24. message.feed_decode()
  25. if message.message.get('displayWatchingCount'):
  26. print("观看人数:" + message.message['displayWatchingCount'])
  27. if message.message.get('displayLikeCount'):
  28. print("点赞人数:" + message.message['displayLikeCount'])
  29. if message.message.get('gift'):
  30. print('收到礼物:')
  31. print(message.message.get('gift'))
  32. if message.message.get('user'):
  33. print('收到弹幕:')
  34. print(message.message.get('user'))
  35. def on_error(ws, error):
  36. print(error)
  37. def on_close(ws):
  38. print("### closed ###")
  39. def on_open(ws):
  40. part1 = [0x08, 0xC8, 0x01, 0x1A, 0x87, 0x01, 0x0A, 0x58] # 不变的头
  41. token = 'cr6mWov8ZD63fX4wkWzb9x5UrmiZRmfeEnllXepWeM7DqbDaDuiHRg5HFWT/ighoL38MgCEi5c2NEmGtjm1BzQ=='
  42. part2 = [ord(c) for c in token]
  43. part3 = [0x12, 0x0B] #
  44. stream_id = "Tdhs47jFHFY"
  45. part4 = [ord(c) for c in stream_id]
  46. part5 = [0x3A, 0x1E]
  47. page_id = get_page_id()
  48. part6 = [ord(c) for c in page_id]
  49. d = part1 + part2 + part3 + part4 + part5 + part6
  50. ws.send(d, websocket.ABNF.OPCODE_BINARY)
  51. def run():
  52. while True:
  53. time.sleep(20)
  54. # 发送心跳-当前时间戳-毫秒
  55. head = [0x08, 0x01, 0x1A, 0x07, 0x08]
  56. timestamp = int(time.time() * 1000)
  57. time_arr = MessageDecode.hex_(timestamp)
  58. heartbeat = head + time_arr
  59. ws.send(heartbeat, websocket.ABNF.OPCODE_BINARY)
  60. thread.start_new_thread(run, ())
  61. if __name__ == "__main__":
  62. websocket.enableTrace(False)
  63. ws = websocket.WebSocketApp("wss://live-ws-pg.kuaishou.com/websocket",
  64. on_message=on_message,
  65. on_error=on_error,
  66. on_close=on_close)
  67. ws.on_open = on_open
  68. ws.run_forever(skip_utf8_validation=True)