How do I select either a th or a td from a table row?

五迷三道 提交于 2019-12-13 07:58:54

问题


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 }


来源:https://stackoverflow.com/questions/44032605/how-do-i-select-either-a-th-or-a-td-from-a-table-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!