gpt4 book ai didi

html - 如何使用 xpath 匹配包含在 html 标记中的链接文本?

转载 作者:行者123 更新时间:2023-12-03 17:36:38 27 4
gpt4 key购买 nike

我有这个链接:

<a href="/stores/non-consequatur-totam/products/search?term=yellow">
Search all categories in
<span style="font-weight: bold;">non consequatur totam's</span>
store for “yellow”
</a>

我正在尝试使用 xpath 匹配它,但我只能使用包含和 text() 匹配跨度之前的部分。我正在使用 capybara 。
page.all(:xpath, "//a[contains(text(), 'Search all categories in')]").first
=> #<Capybara::Element tag="a" path="/html/body/div[2]/div[3]/div[2]/div[1]/p[2]/a[1]">
page.all(:xpath, "//a[contains(text(), 'store for')]").first
=> nil

我如何匹配实际文本,就像 jQuery 一样?我需要忽略内部的 html 标签。我真的很希望能够匹配跨度中的部分。

最佳答案

我认为您正在寻找的是元素的字符串值。元素节点的字符串值只是其所有后代文本节点的串联。

使用表达式 string(//a)几乎(为了避免文本内容中的单引号或双引号出现任何不相关的问题)您显示的 HTML 片段:

<a href="/stores/non-consequatur-totam/products/search?term=yellow">
Search all categories in
<span style="font-weight: bold;">non consequatur totams</span>
store for yellow
</a>

产量
[EMPTY OUTPUT LINE]
Search all categories in
non consequatur totams
store for yellow
[EMPTY OUTPUT LINE]

这就是 a 中的所有文本元素。现在,匹配 a元素的文本内容,测试 string()在谓词中:
//a[normalize-space(string(.)) = 'Search all categories in non consequatur totams store for yellow']

再次应用于稍微修改的输入,这将返回链接元素。
normalize-space()是必要的,因为文本内容包含换行符,而这些字符很难包含在 XPath 表达式中。

要回复您的评论并举另一个例子:

I would really like to be able to use a single contains, assuming I had <a>a b <span>c</span d</div> I would like to look for a b c



我假设你的意思是搜索
<a>a b <span>c</span> d</a>

并寻找 a b c d ?使用上面解释的方法,使用
//a[normalize-space(string(.)) = 'a b c d']

关于html - 如何使用 xpath 匹配包含在 html 标记中的链接文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28256080/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com