编写一个 Java 程序,下载网络漫画 XKCD 的前 100 部漫画。请务必对所有 URL 使用 https://

Write a Java program that downloads the first 100 comics of the webcomic XKCD. Be sure to use https:// for all URLS

这是我目前所拥有的,我无法下载从 https://xkcd.com/1/ and I know I am supposed to be going to the source code for the website. However, I cant seem to figure out how to get all the first 100 comics into my designated file I set it to save to. For example, I want https://xkcd.com/1/(view-source:https://xkcd.com/1/), https://xkcd.com/2/(view-source:https://xkcd.com/2/) 开始一直到第 100 部漫画的 1-100 部漫画。我知道 img src 位于第 50 行,但我又一次不知道如何处理它。

 public static void main(String[] args) {
    URL imgURL = null;
    for (int web = 1; web <= 100; web++) {
    try {
        imgURL = new URL("https://imgs.xkcd.com/comics/barrel_cropped_(1).jpg");
        InputStream stream = imgURL.openStream();
        Files.copy(stream, Paths.get("file/WebComics" + web + ".png"));
        System.out.println("Done!");
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error!");
    }
    }
}

}

将 jsoup 库 jar 添加到您的项目中,然后试试这个:

static void do_page(int id) throws IOException {
    Document doc = Jsoup.connect("https://xkcd.com/" + id).get();
    Elements imgs = doc.select("#comic img");
    for (Element e: imgs) {
        System.out.println(e.attr("src"));
    }
}

然后循环调用do_page函数:

for (int i = 1; i <= 100; i++) {
    do_page(i);
}

现在,您可以再次使用 JSoup 来下载您认为合适的图像,而不是打印它。