我正在使用 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 相同。
如何解决这个问题?
最佳答案
这可能无法完全解决您的问题,因为我不知道整个输入文件可能是什么样子,但我希望这是您可以采取的方向。
from BeautifulSoup import BeautifulSoup, Tag
text = """APPdd34"""
soup = BeautifulSoup(text)
var1 = soup.text
text = """<a href="http://stack.com=APPdd34"> APPdd34</a>"""
soup = BeautifulSoup(text)
var2 = soup.find('a').text
soup = BeautifulSoup("<p>Some new html</p>")
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 提取文本,然后您就可以从那里构建标签。
关于Python 查找和替换 Beautiful Soup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6674310/