从所有元素中获取属性值

时间:2016-04-03 16:47:12

标签: java jsoup

代码:

    Document doc = Jsoup.connect("things.com").get();

    Elements jpgs = doc.select("img[src$=.jpg]");
    String links = jpgs.attr("src"); 

    System.out.print("all: " + jpgs);
    System.out.print("src: " + links);

输出:

all:
<img alt="Apple" src="apple.jpg">
<img alt="Cat" src="cat.jpg">
<img alt="Boat" src="boat.jpg">

src: apple.jpg

Jsoup给出了第一个元素的属性值。我怎样才能得到其他人(cat.jpg和boat.jpg)?

谢谢。

2 个答案:

答案 0 :(得分:1)

public String attr(String attributeKey) { for (Element element : this) { if (element.hasAttr(attributeKey)) return element.attr(attributeKey); } return ""; } 只会返回第一场比赛。

Elements#attr Source Code

Elements

解决方案

要获得所需的结果,您应该遍历for (Element e : jpgs) { System.out.println(e.attr("src")); }

links

答案 1 :(得分:1)

您循环浏览s并通过Element#attr从每个for (Element e : jpgs) { // use e.attr("src") here } 获取,因为Elements#attr(注意List<String>)说:

  

获取具有属性的第一个匹配元素的属性值。

(我的重点。)

例如:

List<String> links = jpgs.stream<Element>()
                             .map(element -> element.attr("src"))
                             .collect(Collectors.toList());

使用Java 8的new Stream stuff,如果你愿意,你可以得到List<String> links = new ArrayList<String>(links.size()); for (Element e : jpgs) { srcs.add(e.attr("src")); } 个:

{{1}}

...但是我的Java 8 streams-fu 非常弱,所以可能不太正确。是的,那不对。但这是一般的想法。

无聊的老式方式是:

{{1}}
相关问题