Eric Eric - 4 months ago 17
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
from
data-original-title
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

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

require 'nokogiri'

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

And, just like a hash, you can assign to it too:

doc.at('div')['class'] = 'bar'
puts doc.to_html 

# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >> <html><body><div class="bar"></div></body></html>

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