首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Dom xpath从html获得第一个锚点href

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

Stack Overflow用户
提问于 2013-09-19 19:49:53
回答 2查看 1.8K关注 0票数 0

下面是HTML:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
$articleLinks   = $finder->query('article[contains(@class,"module_article")]//@href');

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-09-19 19:54:39

使用这个XPATH表达式:

代码语言:javascript
复制
(/article[contains(@class,"module_article")]//@href)[1]

输出:

代码语言:javascript
复制
h/mother-and-baby/2013091914634/vincent-simone-baby-boy-born/

更新(根据上次编辑)

代码语言:javascript
复制
/article[contains(@class,"module_article")]/a[1]/@href

演示示例:

代码语言:javascript
复制
<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

代码语言:javascript
复制
/foo/a[1]/@href

输出:

代码语言:javascript
复制
#1
#3
票数 1
EN

Stack Overflow用户

发布于 2013-09-19 20:05:21

使用<a>检索第一个href

代码语言:javascript
复制
$finder->query('article[contains(@class,"module_article")]/a[1]/@href')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18903682

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档