How to select all cells <th> and <td> alike

css, html-parsing, nokogiri

Solution

You want to use either of the following:

# thang[n] is a Nokogiri <tr> node
cells = thang[n].css('th,td')
cells = thang[n].xpath('./th | ./td')

Note that the CSS version will match any embedded tables (if you had such a horror) while the XPath version will only match direct children of the row.

Problem

Pardon if this is very basic. I have been trying to traverse each cell including header cells in an array of rows. Is there an OR operator I can use in the Nokogiri CSS selector? ``` thang= Nokogiri::HTML(IO.read "|cat page.html").css('table[@id="costbasisTable"] tr') ``` Correctly fetches all rows including a header row (which repeats on subsequent pages): ``` thang[0].inner_html => <th class="tLeft"></th><th>cellA2</th><th>cellA3data</th> thang[1].inner_html => <td>cellB1</td><td>cellB2</td><td>cellB3data</td> ``` The trouble is with the following, which may return blank if that row contains only th's not td's: ``` N=0 thang[N].css("td").map{|c| c.text.strip.gsub(/\t.*/,"").delete ",".tr("&/|:;\n","_")}.to_a ``` What parameter to .css(...) will mean "match any `<td>` OR `<th>` cell"? Is this possible/better done with .xpath() instead for these Nokogiri XML Elements?

Original source