Dom xpath从html获得第一个锚点href

时间:2013-09-19 19:49:54

标签: php dom xpath

这是HTML:

<article class="module_article featured">
    <a title="Exclusive: Strictly's Vincent Simone welcomes baby boy" href="h/mother-and-baby/2013091914634/vincent-simone-baby-boy-born/"><h1 class="article_title">Exclusive: Strictly's Vincent Simone welcomes baby boy</h1></a>        <a href="/healthandbeauty/mother-and-baby/2013091914634/vincent-simone-baby-boy-born/">
        <img src="/imagenes/portadas/1-40-vincent-s.jpg">
    </a>
    <a href="/healthandbeauty/mother-and-baby/2013091914634/vincent-simone-baby-boy-born/">
        <img src="/imagenes/portadas/1-40-vincent-s.jpg">
    </a>
    <p>HELLO! Online can exclusively reveal that&nbsp;Strictly Come Dancing professional Vincent...</p>
</article>
<article class="module_article featured">
    <a title="Exclusive: Strictly's Vincent Simone welcomes baby boy" href="h/mother-and-baby/2013091914634/vincent-simone-baby-boy-born/"><h1 class="article_title">Exclusive: Strictly's Vincent Simone welcomes baby boy</h1></a>        <a href="/healthandbeauty/mother-and-baby/2013091914634/vincent-simone-baby-boy-born/">
        <img src="/imagenes/portadas/1-40-vincent-s.jpg">
    </a>
    <a href="/healthandbeauty/mother-and-baby/2013091914634/vincent-simone-baby-boy-born/">
        <img src="/imagenes/portadas/1-40-vincent-s.jpg">
    </a>
    <p>HELLO! Online can exclusively reveal that&nbsp;Strictly Come Dancing professional Vincent...</p>
</article>

这是我的XPATH:

$articleLinks   = $finder->query('article[contains(@class,"module_article")]//@href');

正如你所看到的,它抓住了hrefs。我只需要第一个。

2 个答案:

答案 0 :(得分:1)

使用此 XPATH 表达式:

(/article[contains(@class,"module_article")]//@href)[1]

输出

h/mother-and-baby/2013091914634/vincent-simone-baby-boy-born/

更新(根据上一次修改)

/article[contains(@class,"module_article")]/a[1]/@href

DEMO示例:

<foo>
  <a href='#1'>1</a>
  <bar>
  <a href='#2'>2</a>
  </bar>
</foo>
<foo>
  <a href='#3'>3</a>
  <baz> <a href='#4'>4</a> </baz>
</foo>

<强> XPATH

/foo/a[1]/@href

<强>输出:

#1
#3

答案 1 :(得分:0)

使用<a>检索第一个href

$finder->query('article[contains(@class,"module_article")]/a[1]/@href')
相关问题