【问题标题】:Jsoup HTML Parsing - Complex Nodes [Java]Jsoup HTML 解析 - 复杂节点 [Java]
【发布时间】:2014-01-27 21:17:23
【问题描述】:

我有这段 HTML:

<td class="my class" >
      <div class="content" style="margin-left:10px;">
        <ul style="list-style-type: disc;">
           <li><span>obj: blue</span></li>
          <li><span>descr: red</span></li>
          <li><span>double: yellow</span></li>
        </ul>
      </div>
</td>

我需要:

obj: blue

descr: red

double: yellow

我已经试过了:

docDescription.select("my.class").text();

但它会返回包含所有文本的块。我需要 3 个不同的部分(逐行)。

【问题讨论】:

    标签: java html parsing jsoup nodes


    【解决方案1】:

    解决方案

    docDescription.select("div > ul > li > span");
    

    说明

    您的文档无效,JSoup 如下所示。 JSoup 总是尝试修复文档。在您的情况下,td 在任何 table 之外,因此将其删除。

    <html>
     <head></head>
     <body> 
      <div class="content" style="margin-left:10px;"> 
       <ul style="list-style-type: disc;"> 
        <li><span>obj: blue</span></li> 
        <li><span>descr: red</span></li> 
        <li><span>double: yellow</span></li> 
       </ul> 
      </div> 
     </body>
    </html>
    

    代码

    public static void main(String[] args) {
        String html = "<td class=\"my class\" >\n" +
                "      <div class=\"content\" style=\"margin-left:10px;\">\n" +
                "        <ul style=\"list-style-type: disc;\">\n" +
                "           <li><span>obj: blue</span></li>\n" +
                "          <li><span>descr: red</span></li>\n" +
                "          <li><span>double: yellow</span></li>\n" +
                "        </ul>\n" +
                "      </div>\n" +
                "</td>";
    
        Elements select = Jsoup.parse(html).select("div > ul > li > span");
        for (Element element : select) {
            System.out.println(element.text());
        }
    }
    

    结果

    obj: blue
    descr: red
    double: yellow
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多