【问题标题】:Retrieve data from Html with JSoup使用 JSoup 从 Html 中检索数据
【发布时间】:2018-02-13 07:13:15
【问题描述】:

我正在尝试从网站检索信息,但问题是类名相同。 这是网站结构。

<tr class="main_el">
<td class="key">KEY1</td>
<td class="val">VALUE1</td>
</tr>

<tr class="main_el">
<td class="key">KEY2</td>
<td class="val">VALUE2</td>
</tr>
...
<tr class="main_el">
<td class="key">KEY3</td>
<td class="val">VALUE3</td>
</tr>

我不能使用这个.get(i).getElementsByClass();,因为每个页面的索引都不同。请帮忙!

编辑 我想仅使用 KEY1 检索 VALUE1 并且独立于其他 VALUES。

注意 VALUE1 可能位于索引 1 或 9

【问题讨论】:

  • 抱歉,问题到底出在哪里?您要检索什么样的信息?如果您需要键值对,您可以简单地解析 元素并对其进行迭代。或者你需要一个特定的?

标签: java html jsoup


【解决方案1】:

你可以这样写简单的函数。

public Map<String, String> parseHtml(String inputHtml) {
    Document.OutputSettings outputSettings = new Document.OutputSettings();
    outputSettings.syntax(Document.OutputSettings.Syntax.html);
    outputSettings.prettyPrint(false);

    Document htmlDoc = Jsoup.parse(inputHtml);

    //Creating map to save td <key,value>

    Map<String, String> textMap = new HashMap<>();

    Elements trElements = htmlDoc.select("tr.main_el");

    if (trElements.size() > 0) {

        for (Element trElement : trElements) {
            String key = null;
            String value = null;

            for (Element tdElement : trElement.children()) {
                if (tdElement.hasClass("key"))
                    key = tdElement.text();
                if (tdElement.hasClass("value"))
                    value = tdElement.text();
            }

            if (key != null && value != null)
                textMap.put(key, value);
        }


    }
    return textMap;
}

然后,您可以通过 html 中的键从地图中检索值。

谢谢。

【讨论】:

    【解决方案2】:

    也许这行得通:

    select all <tr> elements
    for each <tr>
      select <td> with class "key" from the <tr>
      if value of this element == "KEY1" then
        select <td> with class "key" from <tr>
        do whatever you want with this value
    

    【讨论】:

    • 试试吧。如果遇到问题,请针对这些问题提出一个新问题。查看 JSoup 的 select 方法,该方法使用 CSS 选择器从 DOM 中检索元素。
    猜你喜欢
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 2020-04-29
    相关资源
    最近更新 更多