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
Rails 4 Error with Every Command "'Load': No Implicit Conversion of Nil into String" (MAC Os X 10.9)
Validate That String Contains Only Allowed Characters in Ruby
Require Ruby File Without .Rb Extension
Rails: Pundit::Authorizationnotperformederror
Https Request Using Net::Http's Block Form -- Is It Possible
Argumenterror: Unknown Key: :Conditions. Valid Keys Are: :Class_Name, :Class, :Foreign_Key
Array#Rotate Equivalent in Ruby 1.8.7
Accessing a Has_One Associations' Attributes
How to Search for Useful Ruby Gems
Accessing the Child Instance in a Rabl Template
Selenium Webdriver Getting a Cookie Value
How to Click a Link in a Table Based on the Text in a Row
Why Does 'Puts(Nil or 4)' Fail in Ruby