Python寻找并替换美丽的汤

2024-04-20 10:54:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Beautiful Soup将模式的出现替换为HTML文件中的a href link

我面临的问题如下所述

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

样本输入1:

^{pr2}$

样本输入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相同。在

我怎样才能纠正这个问题?在


Tags: 文件comhttpstackhtml模式linkfile
1条回答
网友
1楼 · 发布于 2024-04-20 10:54:22

这可能不能完全回答您的问题,因为我不知道整个输入文件可能是什么样子,但我希望这是您可以采取的一个方向。在

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()

所以基本上,只需使用beauthoulsoup来提取文本,然后就可以从那里构建标记了。在

相关问题 更多 >