简体   繁体   English

Jsoup选择查询具有相同类名的多个元素

[英]Jsoup select query multiple elements with same class name

This how the DOM looks: DOM的外观如下:

<div class="content-section generic-section">
<div class="content-section generic-section">
<div class="content-section generic-section">

I need to fetch the contents from each div elements. 我需要从每个div元素中获取内容。 While using select query all three contents are fetched in same variable. 使用选择查询时,所有三个内容都在同一变量中获取。 how to solve this issue. 如何解决这个问题。

Re this: 重新这样:

While using select query all three contents are fetched in same variable. 使用选择查询时,所有三个内容都在同一变量中获取。

All three would be assigned to an instance of Elements which is a type of ArrayList so, in order to interrogate each of these three elements you could 所有这三个Elements都将分配给一个ArrayList类型的Elements实例,因此,为了询问这三个元素,您可以

  • Iterate over the ArrayList: for (Element element : elements) { ... } 遍历ArrayList: for (Element element : elements) { ... }
  • Select entries by position: elements.get(0) , elements.get(1) etc 按位置选择条目: elements.get(0)elements.get(1)
  • Iterate over Elements using prev() and next() 使用prev()next()遍历Elements
  • Select the first() or last() 选择first()last()
  • Use a visitor pattern to traverse() the Elements 使用访问者模式traverse() Elements
  • Get the text of each of the entries: elements.eachText() 获取每个条目的textelements.eachText()

Even more options in the Javadocs Javadocs中的更多选项

You can get an Elements object using select method. 您可以使用select方法获取Elements对象。 As @glyching mentioned, you can traverse it. 如@glyching所述,您可以遍历它。 I created test code using forEach like as below. 我使用forEach创建了测试代码,如下所示。

public void test() {

    Document doc = Jsoup.parse("<html><body><div class=\"content-section generic-section\">contents1</div><div class=\"content-section generic-section\">contents2</div><div class=\"content-section generic-section\">contents3</div></body></html>");
    // get div elements
    Elements elements = doc.select("div.content-section.generic-section");

    // display "contents1" "contents2" "contents3"
    elements.forEach(element -> System.out.println(element.text()));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM