简体   繁体   English

如何使用Nokogiri解析TABLE文本?

[英]How to parse TABLE text with Nokogiri?

I am using the nokogiri gem to parse an html table content in which I have a column with a list of names and some of those names are hyperlinked and some are not. 我正在使用nokogiri gem解析html表内容,其中有一个带有名称列表的列,其中一些名称是超链接的,而某些则不是。 When I use this code: 当我使用此代码时:

puts doc.xpath("//table//tr//td[1]/text()")

It skips the hyperlinked names. 跳过超链接的名称。 I can also get the hyperlinked names with this: 我也可以这样获得超链接的名称:

doc.xpath('//table//tr//td[1]//a[@href]').each do |link|
   puts link.text.strip
end

How can I get all names without having to do it twice? 如何获得所有名称而不必重复两次?

If you want all text in the cell, hyperlinked or not: 如果要在单元格中显示所有文本,是否具有超链接:

doc.xpath('//td[1]').each do |cell|
   puts cell.text.strip
end

Note: in a valid HTML document, a td will always be within a table and a tr . 注意:在有效的HTML文档中, td始终位于tabletr始终位于table If you don't have any other selector requirements, you can simplify as above. 如果没有其他选择器要求,则可以如上所述进行简化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM