将我的HTML从一种形式转换为另一种形式

时间:2014-11-27 14:15:28

标签: html regex parsing beautifulsoup html-parsing

我刚刚在旧的网页上浏览了一些糟糕的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文件来执行此操作时,以编程方式执行此操作的最佳方法是什么?

由于

3 个答案:

答案 0 :(得分:1)

“以编程方式执行此操作的最佳方法是什么,取决于您最了解的工具。我会用python和beautifulsoup来做。其他人可以保证sed和regex。看我的方法:

创建两个单独的目录,一个包含原始.html文件的&#34; copy&#34; ,另一个目录是修改过的文件(不是原始文件的子目录)。

根据您拥有的内容,在一次运行或单独运行中运行以下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())

答案 1 :(得分:0)

(<([^ ]+)[^<>]+>)([^<]+?)(<\/\2>)

试试这个。\1<h2>\3</h2>\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 :(得分:0)

另一种方法是使用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
}

我希望这会有所帮助。