java - Jsoup选择不同的Div类型并依次处理

标签 java android web-scraping jsoup

嗨,我正在使用 Jsoup 来抓取 html 页面,我有 2 个彼此相邻的 div:

<div class="time_head">... </div>
<div class="blockfix">...  </div>

我需要获取第一个 time_head,然后将其放入其中。第一个 blockfix 中的所有元素,依此类推。

到目前为止我尝试过的:

        Elements time_heads = doc.select("time_head");
        for (Element time_head : time_heads) {

            String the_time_head = Jsoup.parse(String.valueOf(time_head.getElementsByClass("time_head"))).text();
            Log.i("the_time_head ", " Hz:  "+the_time_head);
        }

        Elements blockfixs = doc.select("blockfix");
        for (Element blockfix : blockfixs) {

            String the_blockfix = Jsoup.parse(String.valueOf(time_head.getElementsByClass("blockfix"))).text();
            Log.i("the_blockfix ", " Hz:  "+the_blockfix);
        }

我需要的结果是这样的:

      time_head1:
           ---- blockfix elemts1
           ---- blockfix elemts2
           ---- blockfix elemts3
      time_head2:
           ---- blockfix elemts1
           ---- blockfix elemts2
           ---- blockfix elemts3

最佳答案

看起来您想要迭代所有具有 time_headblockfixdiv 元素,并根据您发现的内容以不同的方式打印它。在这种情况下,您可以将 select(CSSquery)elementA, elementB 之类的查询一起使用,因为 , 在 CSS 中可以被视为 OR 运算符。然后根据当前迭代元素的类名选择如何处理它。

演示:

String html = 
          "<div class='time_head'>time_head content1</div>"
        + "<div class='blockfix'>blockfix1</div>"
        + "<div class='blockfix'>blockfix2</div>"
        + "<div class='time_head'>time_head content2</div>"
        + "<div class='blockfix'>blockfix3</div>"
        + "<div class='blockfix'>blockfix4</div>";

Document doc = Jsoup.parse(html);

for (Element el : doc.select("div.time_head, div.blockfix")) {

    if (el.className().equalsIgnoreCase("time_head")) {
        //handle time_head here
        System.out.println(el.text().toUpperCase());
    }

    if (el.className().equalsIgnoreCase("blockfix")) {
        //handle blockfix here
        System.out.println("----"+el.text());
    }
}

输出:

TIME_HEAD CONTENT1
----blockfix1
----blockfix2
TIME_HEAD CONTENT2
----blockfix3
----blockfix4

关于java - Jsoup选择不同的Div类型并依次处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50799412/

相关文章:

java - 使用 JUnit 比较 2 个对象

Java双重初始化为0

android - VTK 错误在着色器 VAO 和 EGL_BAD_DISPLAY 中设置 'vertexMC'

css - Scrapy Selector CSS 不返回子节点

python - 从 Beautifulsoup4 获取字符串时出现问题

java - "chmod"来自 Java 的 hadoop 路径

java - 如何替换列表中的多个项目?

Android 开发者 - 如何在主屏幕上创建导致操作的按钮

android - Lint 字段从未分配给 Butterknife

vba - Excel VBA : auto click and open file from website