店播爬取Python脚本

data_center_dy_barrage_scraper.py 2.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import time
  2. import threading
  3. import json
  4. from rds_model.rds_dy_barrage_list import RdsDouYinBarrageList
  5. from libs.mysql_dy_live_market_record import MysqlDyLiveMarketRecord
  6. from log.print_log import PrintLog
  7. from libs.dy_barrage_info import DyBarrageInfo
  8. start_time = time.time()
  9. def scrape():
  10. while True:
  11. try:
  12. # 从 待爬取直播间ID 列表中获取一个 直播间ID
  13. room_info = rds.get_request_param()
  14. # 如果没有待爬取的直播,则等一秒,循环
  15. if room_info is None:
  16. time.sleep(1)
  17. continue
  18. # 判断是否到达爬取时间以确定是否需要爬取弹幕,并直接塞回队列尾部
  19. room_dict = json.loads(room_info)
  20. stream_id = str(room_dict['room_id']) # 直播间ID
  21. scrape_time = room_dict['scrape_time'] # 上次抓取时间
  22. # uid = room_dict['uid'] # 直播网红ID
  23. if stream_id is None or scrape_time is None:
  24. time.sleep(1)
  25. continue
  26. room_dict.setdefault('times', 0)
  27. room_dict['times'] = (room_dict['times'] + 1) % 10
  28. if room_dict['times'] == 0: # 每爬取十次判断一次是否需要继续监测
  29. live_info = MysqlDyLiveMarketRecord().new_monitor(stream_id)
  30. if live_info is None: # 直播信息不存在,不再回塞数据到爬取队列
  31. continue
  32. # 直播未结束爬取完成塞回队列
  33. time_diff = int(time.time()) - int(scrape_time)
  34. if time_diff > 1:
  35. # 爬取前更新爬取时间塞回队列
  36. room_dict['scrape_time'] = int(time.time())
  37. rds.push_request_id(json.dumps(room_dict))
  38. response_json = DyBarrageInfo.get_data(stream_id)
  39. if not bool(response_json):
  40. time.sleep(0.1)
  41. continue
  42. else:
  43. data = json.dumps(response_json)
  44. rds.push_data_list(data)
  45. else:
  46. PrintLog.print('直播ID%s %d秒前曾爬取过,暂无需继续抓取' % (stream_id, time_diff))
  47. rds.push_request_id(json.dumps(room_dict))
  48. except Exception as e:
  49. PrintLog.print(time.strftime("%H:%M:%S", time.localtime()) + ' ' + stream_id + '数据异常:' + str(e))
  50. time.sleep(0.1)
  51. if __name__ == "__main__":
  52. print("主方法开始执行")
  53. rds = RdsDouYinBarrageList()
  54. print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' ' + ' 开始执行,待爬取弹幕直播队列长度:' + str(rds.get_len()))
  55. for i in range(1, 20):
  56. task = threading.Thread(target=scrape, name=i)
  57. task.start() # 准备就绪,等待cpu执行