我有這樣的代碼:只能通過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
屬性的值嗎?
我有這樣的代碼:只能通過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
屬性的值嗎?
找到屬性第一
例如: 站點名稱: https://www.easymobilerecharge.com/
我們要找到 「MTS」 鏈接
在你的情況下,找到這個元素,我們可以使用的x路例如: // a [contains(text(),'MTS')]
現在要獲取href屬性,請使用: // a [contains(text(),'MTS')]/@ href
從this question的第一個答案來看,答案似乎是肯定否。它提供了
xml.xpath("//Placement").attr("messageId")
這是非常接近「只有XPath」,但不完全。由你來判斷這對你是否足夠。
你是什麼意思'只有使用XPath'?這個'// a/@ href'是'XPath'來獲得'href'屬性值。 http://videlibri.sourceforge.net/cgi-bin/xidelcgi?&data=%3Ca%20href%3D%27foo.html%27%3Efoo%3C%2Fa%3E%3Ca%20href%3D%27bar.html%27 %3Ebar%3C%2Fa%3E&=&extract =%2F%2Fa%2F%40href&=&input-format = auto&printed-node-format = text&output-format = adhoc&compatibility = Enable%20all%20extensions&dot-notation = unambiguous&extract-kind = xpath3 – Andersson
我想也許有一個xpath類似'// a/@ href/value()'。似乎沒有。謝謝。 – ironsand