【问题标题】:Parse HTML page in Java用 Java 解析 HTML 页面
【发布时间】:2013-02-28 00:08:03
【问题描述】:

我正在解析这个页面片段:

<tr valign="middle">
   <td class="inner"><span style=""><span class="" title=""></span> 2  <span class="icon ok" title="Verified"></span> </span><span class="icon cat_tv" title="Video » TV" style="bottom:-2;"></span> <a href="/VALUE.html" style="line-height:1.4em;">VALUE</a> </td>
   <td width="1%" align="center" nowrap="nowrap" class="small inner" >VALUE</td>
   <td width="1%" align="right" nowrap="nowrap" class="small inner" >VALUE</td>
   <td width="1%" align="center" nowrap="nowrap" class="small inner" >VALUE</td>
</tr>

我在变量 tv 中有这个片段:HtmlElement tv = tr.get(i);

我是这样读取标签&lt;a href="/VALUE.html" style="line-height:1.4em;"&gt;VALUE&lt;/a&gt;的:

HtmlElement a = tv.getElementsByTagName("a").get(0);        
object.name.value(a.getTextContent());

url = a.getAttribute("href");
object.url_detail.value(myBase + url);

如何只读取其他&lt;td&gt;....&lt;/td&gt; 部分的VALUE 字段?

【问题讨论】:

  • 你使用什么框架进行解析?
  • 也许使用 tv.getElementsByTagName("td") 并循环结果并使用 getTextContent() 获取文本内容?你试过了吗?

标签: java html xml xml-parsing html-parsing


【解决方案1】:

我建议使用XPath,这是解析 XML/HTML 的推荐方式

参考:How to read XML using XPath in Java

也看看这个问题:RegEx match open tags except XHTML self-contained tags

更新

如果我理解正确,您需要每个 td 的“VALUE”,对吗? 如果是这样,您的 XPath 将是这样的:

//td[@class="small inner"]/text()

【讨论】:

    【解决方案2】:

    你可以试试一个很棒的java包jsoup

    更新:使用包,你可以解决这样的问题:

        String html = "<tr valign=\"middle\">"
                + "   <td class=\"inner\">"
                + "   <span style=\"\"><span class=\"\" title=\"\"></span> 2  <span class=\"icon ok\" title=\"Verified\"></span> </span><span class=\"icon cat_tv\" title=\"Video » TV\" style=\"bottom:-2;\"></span>"
                + "   <a href=\"/VALUE.html\" style=\"line-height:1.4em;\">VALUE</a> "
                + "   </td>"
                + "   <td width=\"1%\" align=\"center\" nowrap=\"nowrap\" class=\"small inner\" >VALUE</td>"
                + "   <td width=\"1%\" align=\"right\" nowrap=\"nowrap\" class=\"small inner\" >VALUE</td>"
                + "   <td width=\"1%\" align=\"center\" nowrap=\"nowrap\" class=\"small inner\" >VALUE</td>"
                + "</tr>";
        Document doc = Jsoup.parse(html, "", Parser.xmlParser());
        Elements labelPLine = doc.select("a[href]");
        System.out.println("value 1:" + labelPLine.text());
    
        Elements labelPLine2 = doc.select("td[width=1%");
        Iterator<Element> it = labelPLine2.iterator();
        int n = 2;
        while (it.hasNext()) {
            System.out.println("value " + (n++) + ":" + it.next().text());
        }
    

    结果是:

    值 1:值 值 2:值 值 3:值 值 4:值

    【讨论】:

    • 您应该说出如何使用 jsoup 解决问题。否则,这不是一个答案,应该只是一个评论。
    猜你喜欢
    • 1970-01-01
    • 2011-10-09
    • 2013-04-25
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多