【问题标题】:Remove specific tags if are inside specific tag如果在特定标签内,则删除特定标签
【发布时间】:2013-07-30 21:58:20
【问题描述】:

我有一个问题,我必须找到快速的解决方案。

我想删除所有“表格”内部的brp 标签,但不删除外部。

例如

初始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


【解决方案1】:

使用Nokogiri

require 'nokogiri'

doc = Nokogiri::HTML::Document.parse <<-_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>
_HTML_

doc.xpath("//table/tr/td/p").each do |el|
  el.replace(el.text)
end

puts doc.to_html

输出:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<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>
</body>
</html>

【讨论】:

  • 段落标签也需要从表格中移除。
  • 太棒了!我现在就试试!我跟你说个事!谢谢!
  • 有效!非常感谢@Babai !!而且比我的方法快 10000% :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2022-08-23
  • 2018-09-23
相关资源
最近更新 更多