【发布时间】:2013-07-30 21:58:20
【问题描述】:
我有一个问题,我必须找到快速的解决方案。
我想删除所有“表格”内部的br 和p 标签,但不删除外部。
例如
初始html文档:
...
<p>Hello</p>
<table>
<tr>
<td><p>Text example <br>continues...</p></td>
<td><p>Text example <br>continues...</p></td>
<td><p>Text example <br>continues...</p></td>
<td><p>Text example <br>continues...</p></td>
</tr>
</table>
<p>Bye<br></p>
<p>Bye<br></p>
...
我的目标:
...
<p>Hello</p>
<table>
<tr>
<td>Text example continues...</td>
<td>Text example continues...</td>
<td>Text example continues...</td>
<td>Text example continues...</td>
</tr>
</table>
<p>Bye<br></p>
<p>Bye<br></p>
...
现在,这就是我的清洁方法:
loop do
if html.match(/<table>(.*?)(<\/?(p|br)*?>)(.*?)<\/table>/) != nil
html = html.gsub(/<table>(.*?)(<\/?(p|br)*?>)(.*?)<\/table>/,'<table>\1 \4</table>')
else
break
end
end
效果很好,但问题是,我有 1xxx 个文档,每个文档大约有 1000 行……每个文档需要 1-3 个小时。 ((1-3 小时)*(千篇文档)) = ¡痛苦!
我正在寻找使用 Sanitize 或其他方法进行此操作,但目前...我找不到方法。
谁能帮帮我?
提前感谢您! 手动
【问题讨论】:
-
stackoverflow.com/a/1732454/438992 换句话说,使用实际的 HTML 解析器。
-
^ 要添加到上述内容,请考虑使用
Nokogiri。 -
不要使用正则表达式解析 HTML。使用正确的 HTML 解析模块。 您无法使用正则表达式可靠地解析 HTML,并且您将面临悲伤和挫败感。一旦 HTML 与您的期望发生变化,您的代码就会被破坏。有关如何使用已经编写、测试和调试过的 Ruby 模块正确解析 HTML 的示例,请参阅 htmlparsing.com/ruby。
标签: html ruby regex html-parsing