我只能通过 XPath 获取特定属性的值吗?

Can I get value of an specific attribute only by XPath?

我有这样的代码:

doc = Nokogiri::HTML("<a href='foo.html'>foo</a><a href='bar.html'>bar</a>")
doc.xpath('//a/@href').map(&:value) # => ["foo.html", "bar.html"]

一切如我所料。

但是出于好奇我想知道,我是否也可以仅使用 XPath 获取 href 属性的值?

this question 的第一个答案来看,答案似乎是肯定的和否定的。它提供

xml.xpath("//Placement").attr("messageId")

非常接近 "only XPath",但不完全接近。由你来判断这对你来说是否足够。

先定位属性

示例: 站点名称: https://www.easymobilerecharge.com/

我们要定位"MTS"link

对于您的情况,要定位此元素,我们可以使用 x-path,例如: //a[包含(text(),'MTS')]

现在要获取 href 属性,请使用: //a[包含(text(),'MTS')]/@href