douan0729 2018-12-23 22:25
浏览 66
已采纳

在Xpath查询中排除链接

Thinking this should be relatively easy but I'm having trouble finding the right syntax apparently.

Here's what I'm working with minified

$dom = new DOMDocument();
libxml_use_internal_errors(true);

$dom->LoadHTML('<div class="intro"><div class="special"><span class="point"><span class="us">US </span><span>20.00</span></span> per <p class="original"><span class="us">US</span> 7.50 <a href="test.html">Link</a></p></div></div>');

$xp = new DOMXPath($dom);

$path = $xp->query('//div[@class="intro"]');

foreach($path as $p)
{
echo '<pre>';
print_r($p);
echo '</pre>';
}

This brings back

[nodeValue] => US 20.00 per US 7.50 Link

What I'm trying to do is exclude any a or href link elements in the query so the nodeValue simply brings back

[nodeValue] => US 20.00 per US 7.50

Here's a few of what I've tried to achieve this in my xpath query to achieve this:

$path = $xp->query('//div[@class="intro" and not(@href)]');
$path = $xp->query('//div[@class="intro" and not(a)]');
$path = $xp->query('//div[@class="intro"][not(a)]');
$path = $xp->query('//div[@class="intro"][not(@href)]');
$path = $xp->query('//div[@class="intro"][not(self::a)]');

None of these have worked.

What is needed for my query to exclude any link elements in the result?

  • 写回答

1条回答 默认 最新

  • doutang7661 2018-12-23 22:43
    关注

    You can exclude link text nodes from results with

    //div[@class="intro"]//text()[not(parent::a)]
    

    or

    string-join(//div[@class="intro"]//text()[not(parent::a)], " ")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么