【python-爬虫類】bステーション弾幕爬虫類

8110 ワード

# -*- coding:utf-8 -*-
#   :2020/8/3
#   :      
"""
      bilibili     
                
           , ctrl+u        , ctrl+f    room_id
       "room_id":1016 ,1016      
             :     26  roomid         
"""

import requests;
import time;

class Danmu():
    def __init__(self):
        #   url
        self.url = 'https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory';
        #    
        self.headers = {
            'Host':'api.live.bilibili.com',
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0',
        }
        #   POST     
        self.data = {
            'roomid':'1016',
            'csrf_token':'',
            'csrf':'',
            'visit_id':'',
        }
        #      
        self.log_file_write = open('danmu.log',mode='a',encoding='utf-8');
        #     
        log_file_read = open('danmu.log',mode='r',encoding='utf-8');
        self.log = log_file_read.readlines();
        
    def get_danmu(self):
        #        
        html = requests.post(url=self.url,headers=self.headers,data=self.data).json();
        #       
        for content in html['data']['room']:
            #     
            nickname = content['nickname'];
            #     
            text = content['text'];
            #       
            timeline = content['timeline'];
            #     
            msg = timeline+' '+nickname+': '+text;
            #              ,               
            if msg+'
'
not in self.log: # print (msg); # self.log_file_write.write(msg+'
'
); # self.log.append(msg+'
'
); # nickname = ''; text = ''; timeline = ''; msg = ''; # bDanmu bDanmu = Danmu(); while True: # 0.5 cpu time.sleep(0.5); # bDanmu.get_danmu();