Select element by attribute value with XPath in Nokogiri
Asked Answered
S

1

7

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"]')
Sextodecimo answered 28/6, 2014 at 11:20 Comment(2)
it should be @class. Initial dot doesn't make sense in this case.Wort
#2901741Bolen
C
10

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

Carleton answered 3/12, 2014 at 8:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.