【问题标题】:xpath query to parse html tags用于解析 html 标签的 xpath 查询
【发布时间】: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


【解决方案1】:

可能类似于以下内容:

   $remote = file_get_contents('http://www.sitename.com');
    $dom = new DOMDocument();
    //Error suppression unfortunately, as an invalid xhtml document throws up warnings.
    $file = @$dom->loadHTML($remote);

    $xpath = new DOMXpath($dom);

    //Get all data with the user-data class.
    $userdata = $xpath->query('//*[contains(@class, \'user-data\')]');

    //get links
    $links = $xpath->query('//a/@href');

所以要访问这些变量之一,您需要使用nodeValue:

$ret = array();
foreach($userdata as $data) {
  $ret[] = $data->nodeValue;
}

编辑:我想我会提到这将获得所有给定页面上的链接,我想这就是你想要的吗?

【讨论】:

    【解决方案2】:

    使用:

    concat(/td/div/text[1], ' ', /td/div/a)
    

    您可以使用任何您希望在两个字符串之间出现的分隔符来代替上面的 ' '。

    【讨论】:

    • 非常感谢.. 我尝试了您的解决方案,但没有得到我的结果。我已经编辑了这个问题。请检查它。
    猜你喜欢
    • 1970-01-01
    • 2014-02-22
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多