You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求提取非http/https开头的href/src属性URL的XPath表达式

解决XPath提取相对URL(src/href属性)的问题

问题分析

你原来的表达式存在几个关键问题:

  • 使用and逻辑,要求元素同时存在src和href属性且都不满足开头条件,但实际多数元素只有其中一个属性(比如你的示例<script>仅含src),因此匹配不到目标内容。
  • 仅排除了https:开头的情况,未覆盖http://的场景。
  • 选择的是元素节点,而非你需要的属性值。

正确的XPath表达式

直接提取符合条件的src或href属性值,有两种简洁写法:

写法1:分属性匹配后合并

//@src[not(starts-with(., 'http://')) and not(starts-with(., 'https://'))] | //@href[not(starts-with(., 'http://')) and not(starts-with(., 'https://'))]

写法2:先选元素再过滤属性

//*[@src or @href]/@*[name()='src' or name()='href'][not(starts-with(., 'http://')) and not(starts-with(., 'https://'))]

效果验证

针对你的示例节点:

<script async="" src="//d.impactradius-event.com/A2421746-f56c-44ad-9e09-bcf28112e9951.js"></script>

以上表达式会成功提取到属性值://d.impactradius-event.com/A2421746-f56c-44ad-9e09-bcf28112e9951.js

补充说明

如果需要更严格的“相对URL”定义(比如仅匹配以/、./、../开头或无前置斜杠的路径,排除//开头的协议相对URL),可以调整条件为:

//@src[starts-with(., '/') or starts-with(., './') or starts-with(., '../') or not(starts-with(., '/'))] | //@href[starts-with(., '/') or starts-with(., './') or starts-with(., '../') or not(starts-with(., '/'))]

不过根据你的示例需求,第一种表达式已经完全满足要求。

内容的提问来源于stack exchange,提问作者natan specialist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 18:18:18