【问题标题】:Retrieving downloaded link names using jSoup使用 jSoup 检索下载的链接名称
【发布时间】:2015-07-28 21:28:02
【问题描述】:

我正在尝试检索可供下载的 .zip 文件的名称。参考 jSoup "cookbook",我发现该示例使用 "%s (%s)",它返回 hyperlink (download name)。我只想要后一部分,但很难区分两者。到目前为止,这是我所拥有的:

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;
}

【问题讨论】:

    标签: java hyperlink jsoup


    【解决方案1】:

    嗯,我不确定你想通过getNames() 方法中的最后两个循环来实现什么。您可以通过使用 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 (downloadNames.get(y).contains(".zip") &amp;&amp; downloadNames.get(y).startsWith("&lt;http://download")) {

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

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多