使用 jSoup 检索下载的 link 个名称

Retrieving downloaded link names using jSoup

我正在尝试检索可供下载的 .zip 文件的名称。参考 jSoup "cookbook",我发现该示例使用 "%s (%s)",其中 returns 超链接(下载姓名)。我只想要后一部分,但很难区分两者。这是我目前所拥有的:

public static void getNames() throws IOException{

    String url = "http://download.cyanogenmod.org/?device=d855";
    print("Fetching %s...", url);

    Document doc = Jsoup.connect(url).get();
    Elements links = doc.select("a");

    downloadNames = new ArrayList<>();

    // print("\nLinks: (%d)", links.size());
    for (Element link : links) {
        downloadNames.add(print("<%s> (%s)", link.attr("abs:href"), trim(link.text(), 35)));
    }

    int x = 0;
    while (x < downloadNames.size()) {

        // System.out.println(downloadNames.get(x));
        x++;

    }

    uniqueDownloadNames = new ArrayList<>();


    int y = 0;
    while (y < downloadNames.size()) {

        if (downloadNames.get(y).contains(".zip") && downloadNames.get(y).startsWith("<http://download")) {
            uniqueDownloadNames.add(downloadNames.get(y));
        }
        y++;

    }
    int z = 0;
    while (z < uniqueDownloadNames.size()) {

        System.out.println(uniqueDownloadNames.get(z));
        z++;

    }

}

private static String print(String msg, Object... args) {
    // System.out.println(String.format(msg, args));
    String s = String.format(msg, args);
    return s;
}

private static String trim(String s, int width) {
    if (s.length() > width)
        return s.substring(0, width-1) + ".";
    else
        return s;
}

嗯,我不确定你想通过 getNames() 方法中的最后 2 个循环来实现什么。您可以使用 Set 而不是 List 来简单地删除重复的条目。 HashSet 是 Set 接口的实现,只存储唯一的条目。所以你的 getNames() 会变得更短。另外我修改它也只检索第二部分。

public static void getNames() throws IOException {

    String url = "http://download.cyanogenmod.org/?device=d855";
    print("Fetching %s...", url);

    Document doc = Jsoup.connect(url).get();
    Elements links = doc.select("a");

    Set<String> downloadNames = new HashSet<>();

    // print("\nLinks: (%d)", links.size());
    for (Element link : links) {
        downloadNames.add(print("(%s)", trim(link.text(), 35)));
    }

    for (String element : downloadNames) {
        System.out.println(element);
    }

}

小提示:

  • 请看我的迭代循环,以后请用。 while 循环的目的有点不同。

  • 你的版本的错误可能是在这个if:

if (downloadNames.get(y).contains(".zip") && downloadNames.get(y).startsWith("<http://download")) {

您检查了名称是否以 <http://download 开头,但我假设您之前从字符串中删除了该部分。这就是输出为空的原因,因为没有字符串通过此测试。