Java 获取源代码//文件读取器//返回空列表

Java 获取源代码//文件读取器//返回空列表,java,url,arraylist,bufferedreader,Java,Url,Arraylist,Bufferedreader,我正在尝试制作一个网络刮板,收集一年中每天的前100名音乐。目前,我正在尝试编写收集源代码的函数。我几乎只是从我的另一个刮板上复制并粘贴了它,但出于某种奇怪的原因,它返回了一个空列表 我相信我们正在使用函数get_source_code,但我可能错了。不会返回任何错误消息。我们将非常感谢您的帮助,并提前表示感谢 import java.util.ArrayList; import java.io.InputStreamReader; import java.net.URL; import jav

我正在尝试制作一个网络刮板,收集一年中每天的前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;
    }
}

如果您检查了请求的响应代码:

System.out.println(billboardConnection.getResponseCode());
您将看到它返回一个永久移动的301错误代码

有时,为了刮取返回移动错误的URL,您需要遵循重定向URL。但是,在这种情况下,如果检查存储在Location header字段中的重定向URL,您将看到:

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"); 

这是有道理的,谢谢。虽然它是有意义的,但现在我收到了一个新的错误MSG,因为它不是一个HTTPS,它在代码中指定了我必须添加或删除的代码。@ Jblue,您想使用HTTPURLCONTION而不是httpSurLink连接。@ Jblue,如果这个答案已经解决了您的问题,请考虑通过点击复选标记来接受它。这向更广泛的社区表明,您已经找到了一个解决方案,并为您自己和提供该解决方案的用户带来了一定的声誉。没有义务这样做。