Python:转换HTML内容中的引用而不是HTML标记

时间:2013-08-16 13:35:32

标签: python html regex mindtouch

我有一个像这样的HTML:

<pre class="script">template("main/GlobalShared");</pre>
<pre class="script">
var link = '/Draft/Tracker_1.1';
if (wiki.pageexists(link)) {
    &lt;div class="version"&gt; web.link(wiki.uri(link), 'Version 1.1') &lt;/div&gt;
}
</pre>

我需要像这样转换它:

<pre class="script">template(&quot;main/GlobalShared&quot;);</pre>
<pre class="script">
var link = '/Draft/Tracker_1.1';
if (wiki.pageexists(link)) {
    &lt;div class=&quot;version&quot;&gt; web.link(wiki.uri(link), 'Version 1.1') &lt;/div&gt; 
}
</pre>

我一直在摆弄正则表达式,但我似乎无法接近。 我认为我的选择是完全错误的。

如果可能的话,有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

改为使用HTML解析器,然后只需用.replace('"', '&quot;')替换引号。

BeautifulSoup让这项任务变得简单:

from bs4 import BeautifulSoup

soup = BeautifulSoup(htmlsource)

for string in soup.strings:
     string.replace_with(string.replace('"', '&quot;'))

htmlsource = str(soup)
相关问题