Python 查找和替换 Beautiful Soup

标签 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 相同。

如何解决这个问题?

最佳答案

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

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 提取文本,然后您就可以从那里构建标签。

关于Python 查找和替换 Beautiful Soup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6674310/

相关文章:

Python 类 __del__ 方法

javascript - div样式随动画变化?

jquery - 如何使用 jQuery 按文本内容查找元素?

python - 在python的List中通过其成员查找对象

html - 导航栏没有正确的风格

Android:查找动态创建 View 的ID

python - 这是 Post 请求问题还是 SSL 验证问题

python脚本无法读取csv文件并出错 - StopIteration

python - 具有不同列值的 django modelchoicefield

html - 在 HTML5 中包括大写锁定检测