【问题标题】:Getting data in order with Jsoup使用 Jsoup 按顺序获取数据
【发布时间】:2017-06-05 22:31:18
【问题描述】:

我正在尝试从 web 中按顺序从 html 中获取数据。 html代码如下:

<div class="text">

First Text
<br>
<br>
<div style="margin:20px; margin-top:5px; ">
	<table cellpadding="5">
	<tbody><tr>
		<td class="alt2">
				<div>
					Written by <b>excedent</b>
				</div>
				<div style="font-style:italic">quote message</div>
		</td>
	</tr>
	</tbody></table>
</div>Second Text<br>
<br>
<img class="img" src="https://developer.android.com/_static/images/android/touchicon-180.png"><br>
<br>
Third Text
</div>

我想要做的是创建一个 Android 布局抓取 html,但我需要保留元素的顺序。在这种情况下:

  1. TextView => 第一个文本
  2. TextView => 引用消息
  3. TextView => 第二个文本
  4. ImageView => img
  5. TextView => 第三个文本

当我尝试按顺序获取 html 值时,问题就出现了,使用 JSoup 我得到了一个带有“First Text Second Text Third Text”和 Element.ownText 的字符串,最后是 img,结果:

  1. TextView => 第一个文本 第二个文本 第三个文本
  2. TextView => 引用消息
  3. ImageView => img

我该怎么做才能按顺序获取这些数据?

提前致谢

【问题讨论】:

标签: java android web-scraping jsoup


【解决方案1】:

您可以将 html 解析为 html 节点列表。节点列表将保留 DOM 顺序并提供您想要的。

检查parseFragment方法:

这个方法会给你一个节点列表。

【讨论】:

    【解决方案2】:

    试试这个。

        String html = ""
            + "<div class=\"text\">"
            + "    First Text"
            + "    <br>"
            + "    <br>"
            + "    <div style=\"margin:20px; margin-top:5px; \">"
            + "    <table cellpadding=\"5\">"
            + "        <tbody><tr>"
            + "            <td class=\"alt2\">"
            + "                <div>"
            + "                    Written by <b>excedent</b>"
            + "                </div>"
            + "                <div style=\"font-style:italic\">quote message</div>"
            + "            </td>"
            + "            </tr></tbody>"
            + "    </table>"
            + "    </div>Second Text<br>"
            + "        <br>"
            + "        <img class=\"img\" src=\"https://developer.android.com/_static/images/android/touchicon-180.png\"><br>"
            + "        <br>"
            + "        Third Text"
            + "    </div>";
        Document doc = Jsoup.parse(html);
        List<String> rootTexts = doc.select("div.text").first().textNodes().stream()
            .map(node -> node.text().trim())
            .filter(s -> !s.isEmpty())
            .collect(Collectors.toList());
        System.out.println(rootTexts);
    

    输出:

    [First Text, Second Text, Third Text]
    

    【讨论】:

      【解决方案3】:

      这个答案有点晚了,但是做你想做的事情的正确方法是这样。对于最外层的&lt;div&gt;,不要使用Element.children() 获取子元素,而是要使用Element.childNodes()

      Element.children() 只返回子Elements,其中不包含文本。

      Element.childNodes()返回所有子节点,包括TextNodesElements

      这个解决方案对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-16
        • 1970-01-01
        相关资源
        最近更新 更多