使用 Nokogiri 解析表 [英] Parse table using Nokogiri
问题描述
我想使用 Nokogiri 解析一个表.我就是这样做的
def parse_table_nokogiri(html)doc = Nokogiri::HTML(html)doc.search('table > tr').each do |row|row.search('td/font/text()').each do |col|p col.to_s结尾结尾结尾
我有的一些表有这样的行:
<td>一些文字</td></tr>...有些人有这个.
<td><字体>一些文本</font></td></tr>我的 XPath 表达式适用于第二种情况,但不适用于第一种情况.是否有我可以使用的 XPath 表达式,它可以为我提供单元格最内部节点的文本,以便我可以处理这两种情况?
<小时>我已将更改合并到我的代码段中
def parse_table_nokogiri(html)doc = Nokogiri::HTML(html)table = doc.xpath('//table').max_by {|table|table.xpath('.//tr').length}rows = table.search('tr')[1..-1]行.每个做|行|cells = row.search('td//text()').collect {|text|CGI.unescapeHTML(text.to_s.strip)}cell.each 做 |col|把 col把_________"结尾结尾结尾
解决方案使用:
td//text()[normalize-space()]
这将选择当前节点的任何 td
子节点的所有非纯空白文本节点后代(已在代码中选择的 tr
).>
或者,如果您想选择所有文本节点后代,无论它们是否仅包含空格:
td//text()
更新:
OP 在评论中表示他收到了一个不需要的 td
,内容只是一个 ' '
(又名不间断空格).
要排除内容仅由(一个或多个) nbsp 字符组成的 td
,请使用:
td//text()[translate(normalize-space(), ' ', '')]
I would like to parse a table using Nokogiri. I'm doing it this way
def parse_table_nokogiri(html)
doc = Nokogiri::HTML(html)
doc.search('table > tr').each do |row|
row.search('td/font/text()').each do |col|
p col.to_s
end
end
end
Some of the table that I have have rows like this:
<tr>
<td>
Some text
</td>
</tr>
...and some have this.
<tr>
<td>
<font> Some text </font>
</td>
</tr>
My XPath expression works for the second scenario but not the first. Is there an XPath expression that I could use that would give me the text from the innermost node of the cell so that I can handle both scenarios?
I've incorporated the changes into my snippet
def parse_table_nokogiri(html)
doc = Nokogiri::HTML(html)
table = doc.xpath('//table').max_by {|table| table.xpath('.//tr').length}
rows = table.search('tr')[1..-1]
rows.each do |row|
cells = row.search('td//text()').collect {|text| CGI.unescapeHTML(text.to_s.strip)}
cells.each do |col|
puts col
puts "_____________"
end
end
end
解决方案 Use:
td//text()[normalize-space()]
This selects all non-white-space-only text node descendents of any td
child of the current node (the tr
already selected in your code).
Or if you want to select all text-node descendents, regardles whether they are white-space-only or not:
td//text()
UPDATE:
The OP has signaled in a comment that he is getting an unwanted td
with content just a ' '
(aka non-breaking space).
To exclude also td
s whose content is composed only of (one or more) nbsp characters, use:
td//text()[translate(normalize-space(), ' ', '')]
这篇关于使用 Nokogiri 解析表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文
登录
关闭
扫码关注1秒登录
发送“验证码”获取
|
15天全站免登陆