Reputation: 227
I'm just learning how to program in ruby using nokogiri gem.
doc.xpath("//*[@class='someclass']//@href")
will return all href values under "someclass" class somewhere in the HTML.
doc.xpath("//*[@class='someclass']").xpath("//@href")
will return all href in entire HTML.
Could someone explain to me how would someone go about using //@ equivalent in xpath for instance, within parsed data so something like:
doc.xpath("//*[@class='someclass']").xpath(grab all the href within previously parsed)
is possible?
using the *, @ seems to be quite powerful but I can't seem to be able to narrow that down, other than searching through entire HTML, whereever I use it..
as a beginner, I just thought it would be.. intuitive? to be able to use "grab from everywhere" type of syntax limited to what has been parsed previously to narrow down my target, so I can do something like
xpath(whatever).css(whatever).xpath(whatever)
maybe this is not a good practice? maybe with more understanding of parsing concept I would never have to do this? sometimes I find using both xpath and CSS easier..
hopefully someone can enlighten me..
Upvotes: 0
Views: 53
Reputation: 27996
Try changing your second expression from
doc.xpath("//*[@class='someclass']").xpath("//@href")
to
doc.xpath("//*[@class='someclass']").xpath(".//@href")
//
at the beginning of an XPath expression means "descendants of the root of the document," whereas .//
means "descendants of the context node(s)."
You're right that XPath is powerful, and some major aspects of it are intuitive... but there are significant pieces that aren't intuitive, or depend on how your intuition is trained. Careful study reaps dividends, especially if you are going to use XPath much!
Upvotes: 1