【问题标题】:How get all url images in a page with JSoup?如何使用 JSoup 获取页面中的所有 url 图片?
【发布时间】:2015-09-16 19:20:03
【问题描述】:

我正在使用 JSoup 来抓取页面。我通常需要在一个页面或一个页面中获取所有 url 的图像,然后放入 ArrayList<String>。假设如下文件:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>News Page</title>
  </head>
  <body>
    <div class="news">
      <div class="new">
        <div class="image">
          <img src="../images/img01.jpg" />
        </div>
        <div class="info">
          <p class="title">
            Grumpy wizards make toxic brew for the evil Queen and Jack.
          </p>
        </div>
      </div>
      <div class="new">
        <div class="image">
          <img src="../images/img02.jpg" />
        </div>
        <div class="info">
          <p class="title">
            The quick brown fox jumps over the lazy dog.
          </p>
        </div>
      </div>
      <div class="new">
        <div class="image">
          <img src="../images/img03.jpg" />
        </div>
        <div class="info">
          <p class="title">
            Pack my box with five dozen liquor jugs.
          </p>
        </div>
      </div>
     </div>
  </body>
</html>

我是这样做的:

Document document = Jsoup.parse(html);
Elements images = document.select(img);

ArrayList<String> binaryUrls = new ArrayList<String>();
for(Element image : images) {
    binaryUrls.add(image.absUrl("src"));
}

结果:

['http//www.newssite.com/images/img01.jpg', 'http//www.newssite.com/images/img02.jpg', 'http//www.newssite.com/images/img03.jpg']

它有效,但我想知道是否存在一条捷径,只需使用 Jsoup 即可。

在生产环境中,我们使用的是 Java 6。如果可能的话,我喜欢知道 Java 6 模式和 Java 8 模式,以及 lambda。

【问题讨论】:

    标签: java web-crawler jsoup


    【解决方案1】:

    没有对 Java6 的建议。

    在 Java 8 中使用 Lambda:

    ArrayList<String> binaryUrls = Jsoup.parse(html).select("img")
        .stream().map(p -> p.absUrl("src"))
        .collect(Collectors.toCollection(ArrayList::new));
    

    或者如果返回类型可以只是List&lt;String&gt;:

    List<String> binaryUrls = Jsoup.parse(html).select("img")
        .stream().map(p -> p.absUrl("src"))
        .collect(Collectors.toList());
    

    【讨论】:

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