【发布时间】:2011-04-18 03:36:50
【问题描述】:
我需要使用 xpath 查询解析以下示例 html。
<td id="msgcontents">
<div class="user-data">Just seeing if I can post a link... please ignore post
<a href="http://finance.yahoo.com">http://finance.yahoo.com</a>
</div>
</td>
<td id="msgcontents">
<div class="user-data">some text2...
<a href="http://abc.com">http://abc.com</a>
</div>
</td>
<td id="msgcontents">
<div class="user-data">some text3...
</div>
</td>
上面的 html 可以在一个页面中重复 n 次。
有时 ..... 部分可能不存在,如上述 html 块所示。
我需要的是 xpath 语法,以便我可以将解析的字符串作为
array1[0]= "Just seeing if I can post a link... please ignore post ttp://finance.yahoo.com"
array[1]="some text2 htp://abc.com"
array[2]="sometext3"
【问题讨论】:
-
(1) 您可以使用“代码”按钮来缩进您的 HTML 代码,以便它使用尖括号呈现而不会损坏它。 (2)你的问题是模棱两可的,因为href属性与锚文本具有相同的值,并且你没有明确你在追求哪一个。 (3) HTML 不一定是有效的 XML,因此请理解使用 XPATH(需要 XML)可能不是闲置的路线,除非您可以将所有 HTML 哄骗成有效的 XML。
-
选择此类
div元素的XPath 是/html/body/table/tr/td/div[@class='user-data']。然后你需要每个节点的字符串值。这取决于宿主语言的 DOM 方法。
标签: dom xpath html-parsing