Jsoup 无法从 html 表中提取格式

Jsoup Trouble extracting formatting from html tables

<tr>

<th align="LEFT" bgcolor="GREY"> <span class="smallfont">Higher-order 
Theorems</span>

</th><th bgcolor="PINK"> <em><a href="\ 
[http://www.tptp.org/CASC/J9/SystemDescriptions.html#Satallax---3.2\] 
(http://www.tptp.org/CASC/J9/SystemDescriptions.html#Satallax-- 
-3.2)">Satallax</a><br><span class="xxsmallfont">3.2</span></em>

</th><th bgcolor="SKYBLUE"> <a href="\ 
[http://www.tptp.org/CASC/J9/SystemDescriptions.html#Satallax---3.3\] 
(http://www.tptp.org/CASC/J9/SystemDescriptions.html#Satallax-- 
-3.3)">Satallax</a><br><span class="xxsmallfont">3.3</span>

</th><th bgcolor="LIME"> <a href="\ 
[http://www.tptp.org/CASC/J9/SystemDescriptions.html#Leo-III---1.3\] 
(http://www.tptp.org/CASC/J9/SystemDescriptions.html#Leo-III-- 
-1.3)">Leo‑III</a><br><span class="xxsmallfont">1.3</span>

</th><th bgcolor="YELLOW"> <a href="\ 
[http://www.tptp.org/CASC/J9/SystemDescriptions.html#LEO-II---1.7.0\] 
(http://www.tptp.org/CASC/J9/SystemDescriptions.html#LEO-II-- 
-1.7.0)">LEO‑II</a><br><span class="xxsmallfont">1.7.0</span>

</th></tr>

假设我想提取 bgcolor、对齐以及范围 class 中包含的内容。例如 GREY,LEFT,Higher-order Theorems.

如果我只想提取至少 bgcolor,但最好是全部 3 个,我该怎么做?

所以我试图只提取 bgcolor 和

我试过了 doc.select("tr:contains([bgcolor]"), doc.select(th, [bgcolor], doc.select([bgcolor]), doc.select (tr:containsdata(bgcolor) 以及 doc.select([style]) 并且都没有返回任何输出或返回了解析错误。我可以提取跨度 class 中的内容,但很好更重要的是还提取 bgcolor 和对齐。

你只需要解析你想要的 HTML 代码到 JSOUP 中,然后 select 你想要的 HTML 标签的属性,使用 attr select 或来自 JSOUP 元素,它为您提供 HTML 中每个标签的属性值。要同时检索 span 标签之间包含的文本,您需要 select 第 th 中的嵌套 span 并获取 .text().

    Document document = Jsoup.parse(YOUT HTML GOES HERE);
    System.out.println(document);
    Elements elements = document.select("tr > th");

    for (Element element : elements) {
        String align = element.attr("align");
        String color = element.attr("bgcolor");
        String spanText = element.select("span").text();

        System.out.println("Align is " + align +
                "\nBackground Color is " + color +
                "\nSpan Text is " + spanText);
    }

如需更多信息,请随时问我!希望对您有所帮助!

评论的更新答案:

为此,您需要在 for each 循环中使用这一行:

String fullText = element.text();

这样您可以获得 selected 元素标记之间包含的所有文本,但您应该查找 this blog 并使您想要的查询适合它。我想您还需要检查字符串是否为空,并使用 IF 条件对每种可能的情况进行单独查询。

这意味着有一个用于此结构:tr > th > span,另一个用于此结构:tr > th > em,另一个用于:tr > th.