Eric Eric - 1 year ago 159
Ruby Question

How to get the value of an attribute using Nokogiri

I am trying to get the value

3:40 AM - 1 Mar 2016
within the following block of code using Nokogiri:

<span class="ProfileHeaderCard-joinDateText js-tooltip u-dir" dir="ltr" data-original-title="12:40 PM - 1 Mar 2016">Joined March 2016</span>

I successfully reach the global node:

[#<Nokogiri::XML::Element:0x3ff7899f7b60 name="span" attributes=[#<Nokogiri::XML::Attr:0x3ff7899f9ec4 name="class" value="ProfileHeaderCard-joinDateText js-tooltip u-dir">, #<Nokogiri::XML::Attr:0x3ff7899f9e9c name="dir" value="ltr">, #<Nokogiri::XML::Attr:0x3ff7899f9e88 name="title" value="3:40 AM - 1 Mar 2016">] children=[#<Nokogiri::XML::Text:0x3ff7899f8790 "Joined March 2016">]>]

But I can't reach this specific value.

Answer Source

It's idiomatic to access parameter values by treating the node as a hash:

require 'nokogiri'

doc = Nokogiri::HTML('<div class="foo"></div>')'div')['class'] # => "foo"

And, just like a hash, you can assign to it too:'div')['class'] = 'bar'
puts doc.to_html 

# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "">
# >> <html><body><div class="bar"></div></body></html>

See [] and []= "Modifying Nodes and Attributes" in the documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download