天天看點

java爬蟲爬取B站彈幕

  1. 首先建立一個maven項目,并導入Jsoup包`
<dependencies>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.3</version>
        </dependency>
    </dependencies>
           
  1. 去B站找到你想要爬彈幕的視訊頁面
    java爬蟲爬取B站彈幕

右鍵點選檢視網頁源代碼

按Ctrl + F輸入cid 搜尋

java爬蟲爬取B站彈幕

找到并複制cid的值

http://comment.bilibili.com/20746041.xml

将你擷取的cid替換.com後面的數字,然後這個xml檔案就是該視訊的所有彈幕

  1. 接下來就是JAVA代碼了
public class Demo {
    public static void main(String args[]) throws IOException {
    	//擷取整個頁面
        Document document = Jsoup.connect("http://comment.bilibili.com/20746041.xml").get();
        //擷取所有的d标簽   也就是存放彈幕的标簽  
        Elements d = document.getElementsByTag("d");
        //擷取File
        File file = new File("D://盧本偉.txt");
        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream fileOutputStream=new FileOutputStream(file);
        //周遊所有的d标簽
        for(Element element: d){
       		//擷取每條彈幕換行并添加到txt檔案中
            fileOutputStream.write((element.text()+"\r\n").getBytes());
        }
        fileOutputStream.close();
    }
}
           

是不是很簡單

右鍵運作,然後打開路徑對應的檔案就像下面這樣,就擷取到整個視訊的彈幕啦

L B W N B

java爬蟲爬取B站彈幕