How do I select either a th or a td from a table r

2019-09-20 03:41发布

问题:

I'm using Nokogiri with Rails 5. How do I select either a "th" element or a "td" element from a table row? My goal is to get all the text of cells in a row (if there is a more generic, elegant solution, I'm all in). Here's what I have

      text_all_rows = all_rows.map do |row|
        row_values = row.css('td | th').map{|str| str.text }
                                  .map{|str| str.gsub(/[[:space:]]+/, ' ').gsub(/\A\p{Space}+|\p{Space}+\z/, '') }.join("\t")
        [*row_values]
      end

As you may have noticed "td | th" is not valid syntax for selecting the "th" or "td" elements from the row.

回答1:

Use a , (comma) to select multiple nodes:

row_values = row.css('td, th').map{|str| str.text }