2017-08-03 32 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