2017-08-03 36 views
0

我正在試圖製作一個網絡抓取工具,用於收集每年每天的前100首音樂。目前我正在嘗試編寫收集源代碼的函數。我幾乎只是複製並從我的另一個刮板粘貼它,但由於一些奇怪的原因,它返回一個空列表。獲取源代碼//文件讀取器//返回空列表

我相信我們正在使用函數get_source_code,但我可能是錯的。沒有錯誤消息被返回。預先感謝您的幫助。

import java.util.ArrayList; 
import java.io.InputStreamReader; 
import java.net.URL; 
import java.util.List; 
import javax.net.ssl.HttpsURLConnection; 
import java.io.BufferedReader; 
import java.io.IOException; 

public class MusicScraper { 
    public static void main(String [] args)throws IOException { 
     parse_source_code(get_source_code("","","")); 

    } 
    public static List<String> get_source_code(String day, String month, String year)throws IOException{ 
     List <String> sourceC = new ArrayList<>(); 

     URL link = new URL("https://www.billboard.com/charts/hot-100/2017-02-25");    //"http://www.billboard.com/charts/hot-100/" + year + "-" + month + "-" + day); 

     HttpsURLConnection billboardConnection = (HttpsURLConnection) link.openConnection(); 
     billboardConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); 
     billboardConnection.connect(); 

     BufferedReader in = new BufferedReader(new InputStreamReader(billboardConnection.getInputStream())); 

     String inputLine; 
     while ((inputLine = in.readLine()) != null) { 
      sourceC.add(inputLine); 
     } 
     System.out.println(sourceC); 
     return sourceC; 
    } 

    public static List<String> parse_source_code(List<String> sourceCode){ 
     List<String> data = new ArrayList<>(); 

     List<String> rank = new ArrayList<>(); 
     List<String> song = new ArrayList<>(); 
     List<String> artist = new ArrayList<>(); 

     for (int i = 0; i < sourceCode.size(); i++) { 
      if (sourceCode.get(i).contains("data-songtitle=\"")) { 
       String parsedSong = sourceCode.get(i).split("data-songtitle=\"")[1].split("\">")[0]; 
       song.add(parsedSong); 
      } 

} 
     System.out.println(song); 
     return sourceCode; 
    } 
} 

回答

1

如果你檢查你請求的響應代碼:

System.out.println(billboardConnection.getResponseCode()); 

你會看到它返回一個301錯誤代碼(永久移動)。

有時爲了颳去返回移動錯誤的網址,您需要遵循重定向網址。然而,在這種情況下,如果你檢查重定向URL(存儲在Location頭字段),你會看到:

http://www.billboard.com/charts/hot-100/2017-02-25 

這意味着您的請求正在從https降級到HTTP,所以你可以很容易地解決您的問題通過首先使用http:

URL link = new URL("http://www.billboard.com/charts/hot-100/2017-02-25"); 
+0

這是有道理的,謝謝。雖然它是有道理的,我現在收到一個新的錯誤消息,因爲它不是代碼中指定的https,我必須添加或刪除代碼。 – Jblue

+0

沒關係我非常感謝你。 – Jblue

+0

@Jblue你想使用'HttpURLConnection'而不是'HttpsURLConnection'。 – explv