Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select element by attribute value with XPath in Nokogiri

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"]')
like image 575
ruben1 Avatar asked Jun 28 '14 11:06

ruben1


1 Answers

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

like image 62
Linjie Avatar answered Nov 02 '22 12:11

Linjie