Ruby – Select element by attribute value with XPath in Nokogiri

nokogirirubyxpath

So if I have this piece of code

<body>
  <div class="red">
    <a href="http://www.example.com>Example</a>
  </div>
</body>

I know that I want to get an element with the attribute "class" and value "red" but I don't know where is located.

If I used XPath, is this piece of code right?

dir = "http://www.domain.com"
doc = Nokogiri::HTML(open(url))
doc.xpath('.//*[class="red"]')

I'm just learning so I don't know if any of this is wrong. I can't make it work. Thanks.

Edit: Now it's working =)

doc.xpath('//*[@class="red"]')

Best Answer

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