【问题标题】:How to take outer td data when the td has inner table JSouptd有内表JSoup时如何取外td数据
【发布时间】:2014-09-04 09:31:45
【问题描述】:

我正在使用 JSoup 进行网页抓取。我有一个类名为.chart 的表,其中有行(tr),行有数据(td)。但是一些 tds 里面有表格,里面也包含行和 tds。这是这些有问题的 td 之一的形式:

<td align="center" onmouseout="hideAlt(104692)" onmouseover="showAlt(104692)">
21
<div id="as104692" class="altsrc" style="height: 32px; top: 308px; left: 622px; display: none;">
<b>Alt Src Locations</b>
<br>
<table class="none" border="0">
<tbody>
<tr>
<td>Lisac's Tire Butte</td>
<td align="right">21</td>
</tr>
</tbody>
</table>
</div>

这就是我获取数据的方式:

Elements e = manuf.select("table.chart tr");
            for(Element el : e) {
                Elements columns = el.select("td");
                for(Element c : columns) {
                    System.out.print(c.text() + ", ");
                }
}

这是我得到的结果:21 Alt Src Locations Lisac's Tire Butte 21 这就是我想要的结果:21

我怎样才能告诉程序只接受第一个 td 而不是把那些放在里面?

【问题讨论】:

    标签: html jsoup


    【解决方案1】:

    您可以通过 ownText()immediate child 选择器的组合实现您想要的效果

    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    import org.jsoup.select.Elements;
    
    public class Main {
    
        public static void main(String[] args) {
            try {
                String html = "<table class=\"chart\">" +
                              "<tr>" +
                              "<td align=\"center\" onmouseout=\"hideAlt(104692)\" onmouseover=\"showAlt(104692)\">" +
                              "21" +
                              "<div id=\"as104692\" class=\"altsrc\" style=\"height: 32px; top: 308px; left: 622px; display: none;\">" +
                              "<b>Alt Src Locations</b>" +
                              "<br>" +
                              "<table class=\"none\" border=\"0\">" +
                              "<tbody>" +
                              "<tr>" +
                              "<td>Lisac's Tire Butte</td>" +
                              "<td align=\"right\">21</td>" +
                              "</tr>" +
                              "</tbody>" +
                              "</table>" +
                              "</div>" +
                              "</td>" +
                              "</tr>" +
                              "</table>";
    
                Document doc = Jsoup.parse(html);
    
                Elements els = doc.select("table.chart>tbody>tr>td");
                for(Element el: els) 
                    System.out.println(el.ownText());
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

    • 我猜 >tbody> 是隐式的,因为代码可以工作(它打印第一个 的文本),尽管在该部分没有明确的 标签树。
    • 其实有。 Jsoup 的 html 解析器(默认)将添加缺失的标签或删除无效的标签,因此它创建的结果 dom 符合 html 规范。尝试打印我的示例中的 doc 变量,您会看到它。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签