【问题标题】:Converting my HTML from one form to another将我的 HTML 从一种形式转换为另一种形式
【发布时间】:2015-01-26 04:08:56
【问题描述】:

我只是在旧网页上浏览一些糟糕的 HTML 标记。我注意到我的标记经常出现一些错误。

我希望用一个程序来解决这些问题,但我不确定什么 API 或语言可以帮助我完成这个。有人能帮帮我吗?

我的 HTML 是这种形式:

<td class="bulletPoint" align="right" valign="top" height="100%" width="100%">This is text</td>

我想要替换的

<td class="bulletPoint" align="right" valign="top" height="100%" width="100%"><h2>This is text</h2></td>

我也有这种形式(class/colspan/href 可以变化):

<td class='original' colspan=4><a id='id12345' class='content' href='#note'">This is the text</a> 

并希望将其转换为:

<font SIZE="3"  COLOR="#222222"  FACE="Verdana"  STYLE="background-color:#ffffff;font-weight: bold;"><h2>This is the text</h2></font>

当我有超过 1,000 个 .html 文件来执行此操作时,以编程方式执行此操作的最佳方法是什么?

谢谢

【问题讨论】:

  • &lt;font&gt; 已弃用;你不应该在新代码中使用它。
  • 创建 1 个 css 属性文件并从所有文件中删除内联 html 属性肯定更容易吗?
  • 不确定你想对第二行做什么,但只要 ... 在一行上,这应该适用于第一个替换 cat file.html | sed 's;\(&lt;td class="bulletPoint" .*&gt;\)\(.*[~&lt;]\)\(.*\);\1&lt;h2&gt;\2/h2&gt;&lt;\3;g'
  • 使用正则表达式替换所有。该功能存在于大多数 IDE 和许多文本编辑器中。不过,您需要对所需的不同输出进行 2 次单独替换,只需确保正则表达式足够具体,仅匹配您想要的输出即可
  • 您在第 3 行缺少 ,我猜您正试图用第 4 行包装所有“这是文本”。是这样吗? (已弃用 问题 appart)

标签: html regex parsing beautifulsoup html-parsing


【解决方案1】:
(<([^ ]+)[^<>]+>)([^<]+?)(<\/\2>)

试试这个。替换为\1&lt;h2&gt;\3&lt;/h2&gt;\4。查看演示。

http://regex101.com/r/vF0kU2/6

import re
p = re.compile(ur'(<([^ ]+)[^<>]+>)([^<]+?)(<\/\2>)')
test_str = u"<td class=\"bulletPoint\" align=\"right\" valign=\"top\" height=\"100%\" width=\"100%\">This is text</td>\n<td class='original' colspan=4><a id='id12345' class='content' href='#note'\">This is the text</a> "
subst = u"\1<h2>\3</h2>\4"

result = re.sub(p, subst, test_str)

【讨论】:

    【解决方案2】:

    另一种方法是使用HtmlAgilityPack 更改您的文件。

    我已经做过几次了。我不确定您对 .NET 和 C# 的熟悉程度。下面是一些可以帮助您入门的伪代码:

    using HtmlAgilityPack;
    
    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(htmlFromFile);
    
    IList<HtmlNode> tableDataCells = doc.DocumentNode.Descendants("td").Where(x =>x.Attributes["class"] == "bulletPoint").ToList();
    foreach (HtmlNode td in tableDataCells)
    {
        // add code to insert h2 tag into data cell
    }
    

    我希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      “以编程方式实现的最佳方式是什么”取决于您最了解哪些工具。我会用python和beautifulsoup来做。其他人可能会担保 sed 和正则表达式。看我的方法:

      创建两个单独的目录,一个包含原始 .html 文件的“副本”,另一个包含修改后的文件所在的位置(不是原始文件的子目录)。

      根据你所拥有的,一次运行或单独运行以下 python3 程序。您并没有更改原始文件,您可以随时删除修改后的文件并重试。

      您可以根据需要更改 class_、colspan、href 等的选择,还可以创建多个程序,为您可能遇到的每种情况创建一个程序。

      import os
      from bs4 import BeautifulSoup
      
      do = dir_with_original_files = '/path/to/your_original_files'
      dm = dir_with_modified_files = '/path/to/your_modified_files'
      for root, dirs, files in os.walk(do):
          for f in files:
              if f.endswith('~'): #you don't want to process backups
                  continue
              original_file = os.path.join(root, f)
              mf = f.split('.')
              mf = ''.join(mf[:-1])+'_mod.'+mf[-1] # you can keep the same name 
                                                   # if you omit the last two lines.
                                                   # They are in separate directories
                                                   # anyway. In that case, mf = f
              modified_file = os.path.join(dm, mf)
              with open(original_file, 'r') as orig_f, \
                   open(modified_file, 'w') as modi_f:
                  soup = BeautifulSoup(orig_f.read())
                  for t in soup.find_all('td', class_='bulletPoint'):
                      t.string.wrap(soup.new_tag('h2'))
                  # The following loop could belong to a separate python progam
                  # which would follow the same general structure.
                  for t in soup.find_all('td', class_='original'):
                      font = soup.new_tag('font')
                      font['size'] = '3'
                      font['color'] = '#222222'
                      font['face'] = 'Verdana'
                      font['style'] = 'background-color:#ffffff;font-weight: bold;'
                      t.string.wrap(soup.new_tag('h2')).wrap(font)
                  # This is where you create your new modified file.
                  modi_f.write(soup.prettify())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-11
        • 2020-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-13
        • 1970-01-01
        相关资源
        最近更新 更多