Nokogiri allows you to associate .css() and .xpath() calls with the same object. So anytime you like to use :has , just end the current .css() call and add .xpath(..) (the parent selector). You can even renew your choice with another .css() call, starting with your xpath() stopped!
Example:
Here are some HTML from Wikipedia:
<tr> <th scope="row" style="text-align:left;"> Origin </th> <td> <a href="/wiki/Edinburgh" title="Edinburgh">Edinburgh</a> <a href="/wiki/Scotland" title="Scotland">Scotland</a> </td> </tr> <tr> <th scope="row" style="text-align:left;"> <a href="/wiki/Music_genre" title="Music genre">Genres</a> </th> <td> <a href="/wiki/Electronica" title="Electronica">Electronica</a> <a href="/wiki/Intelligent_dance_music" title="Intelligent dance music">IDM</a> <a href="/wiki/Ambient_music" title="Ambient music">ambient</a> <a href="/wiki/Downtempo" title="Downtempo">downtempo</a> <a href="/wiki/Trip_hop" title="Trip hop">trip hop</a> </td> </tr> <tr> <th scope="row" style="text-align:left;"> <a href="/wiki/Record_label" title="Record label">Labels</a> </th> <td> <a href="/wiki/Warp_(record_label)" title="Warp (record label)">Warp</a> <a href="/wiki/Skam_Records" title="Skam Records">Skam</a> <a href="/wiki/Music70" title="Music70">Music70</a> </td> </tr>
Suppose you want to select all the <a> elements inside the first <td> that appears after the <th> containing the link with href="/Music_genre" .
@artistPage.css("table th > a[href='/wiki/Music_genre']").xpath("..").css("+ td a")
This will return all <a> for each list of genres.
Now for a good measure, let me grab the inner text of all these <a> and put them in an array.
@genreLinks = @artistPage.css("table th > a[href='/wiki/Music_genre']").xpath("..").css("+ td a") @genres = [] @genreLinks.each do |genreLink| @genres.push(genreLink.text) end
source share