Python Find&取代美丽的汤

时间:2011-07-13 05:03:01

标签: python html find beautifulsoup

我使用Beautiful Soup用HTML文件中的href链接替换模式的出现

我遇到如下所述的问题

modified_contents = re.sub("([^http://*/s]APP[a-z]{2}[0-9]{2})", "<a href=\"http://stack.com=\\1\">\\1</a>", str(soup))

示例输入1:

Input File contains APPdd34

Output File contains <a href="http://stack.com=APPdd34"> APPdd34</a>

示例输入2:

Input File contains <a href="http://stack.com=APPdd34"> APPdd34</a>

Output File contains <a href="http://stack.com=<a href="http://stack.com=APPdd34"> APPdd34</a>"> <a href="http://stack.com=APPdd34"> APPdd34</a></a>

所需的输出文件2与样本输入文件2相同。

我该如何纠正这个问题?

1 个答案:

答案 0 :(得分:0)

这可能无法完全解决您的问题,因为我不知道整个输入文件看起来像,但我希望这是您可以采取的方向。

from BeautifulSoup import BeautifulSoup, Tag
text = """APPdd34"""
soup = BeautifulSoup(text)
var1 = soup.text
text = """&lt;a href="http://stack.com=APPdd34"&gt; APPdd34&lt;/a&gt;"""
soup = BeautifulSoup(text)
var2 = soup.find('a').text

soup = BeautifulSoup("&lt;p>Some new html&lt;/p&gt;")
tag1 = Tag(soup, "a",{'href':'http://stack.com='+var1,})
tag1.insert(0,var1) # Insert text
tag2 = Tag(soup, "a",{'href':'http://stack.com='+var2,})
tag2.insert(0,var2)
soup.insert(0,tag1)
soup.insert(3,tag2)
print soup.prettify()

基本上,只需使用BeautifulSoup提取文本,然后就可以从那里构建标签。