Ruby Xpath to Find Attribute

Ruby XPath to find Attribute

Your starting point would be REXML

The "challenge" here is how to treat an attribute node as a child node, and this can be done by using singleton methods, then everything else follows naturally:

require "rexml/document"
include REXML # so that we don't have to prefix everything with REXML::...

def get_pair(xml_doc, key, value)
XPath.each(xml_doc, key) do |node|
if node.is_a?(Attribute)
def node.parent
self.element
end
end
puts "\"#{node}\" \"#{XPath.first(node, value)}\""
end
end

xml_doc = Document.new <<EOF
<root>
<add key="A" value="B" />
<add key="C" value="D" />
<add foo="E" bar="F" />
</root>
EOF

get_pair xml_doc, "//*/@key", "../@value"
get_pair xml_doc, "//*/@foo", "../@bar"

produces:

"A" "B"
"C" "D"
"E" "F"

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

Locate attributes first

example:
site name:
https://www.easymobilerecharge.com/

We want to locate "MTS" link

In your case, to locate this element, we can use x-path like:
//a[contains(text(),'MTS')]

Now to get href attribute, use:
//a[contains(text(),'MTS')]/@href

Select element by attribute value with XPath in Nokogiri

Change class to @class. Remove the dot in the beginning. Then it will work.

Get XML attribute value of property using XPath

This XPath,

//property[@name='timestamp']/@value

will select all value attributes of property elements with a name attribute value equal to 'timestamp'.

Find a node with a specific 'style' attribute xpath in Ruby

It scans all elements and return those which have top:1px in style attribute.

//*[contains(@style, 'top:1px')]

How to find element by attribute value?

You can simply use the following XPath expression to get the issue element having a child element where id equals 6:

//issue[id=6]

id is a child element, not an attribute so you don't use @id for this task.

Ruby/Selenium xpath html attribute

That is not attribute. Using proper selector and getting text should work

Selector: h2>em

Use

title = driver.find_element(:css, "h2>em").text

XPATH selecting node with attribute and text

That works with nokogiri 1.5, Are you using a very old version?



Related Topics



Leave a reply



Submit