Python BeautifulSoup - 在找到的关键字周围添加标签

时间:2013-02-01 18:26:22

标签: python html insert tags beautifulsoup

我目前正在开展一个项目,我希望在一个大量的HTML文件中允许正则表达式搜索。

在首先查明我感兴趣的文件后,我现在想要突出显示找到的关键字!

使用BeautifulSoup我可以确定找到关键字的节点。我做的一件事就是改变整个父母的颜色。

但是,我还想在我找到的关键字周围添加自己的< span> -Tags。

使用find() - BFSoup提供的函数确定位置并不是什么大不了的事。但是在常规文本周围添加我的标签似乎是不可能的?

# match = keyword found by another regex
# node = the node I found using the soup.find(text=myRE)
node.parent.setString(node.replace(match, "<myspan>"+match+"</myspan>"))

这样我只会添加纯文本而不是正确的标签,因为文档没有新解析,我希望避免使用!

我希望我的问题变得有点明确:)

2 个答案:

答案 0 :(得分:3)

这是一个简单的例子,显示了一种方法:

import re
from bs4 import BeautifulSoup as Soup

html = '''
<html><body><p>This is a paragraph</p></body></html>
'''

(1)存储文本并清空标签

soup = Soup(html)
text = soup.p.string
soup.p.clear()
print soup

(2)获得要加粗的词的开头和结尾位置(为我的英语道歉)

match = re.search(r'\ba\b', text)
start, end = match.start(), match.end()

(3)拆分文本并添加第一部分

soup.p.append(text[:start])
print soup

(4)创建一个标签,向其添加相关文本并将其附加到父母

b = soup.new_tag('b')
b.append(text[start:end])
soup.p.append(b)
print soup

(5)追加文本的其余部分

soup.p.append(text[end:])
print soup

这是上面的输出:

<html><body><p></p></body></html>
<html><body><p>This is </p></body></html>
<html><body><p>This is <b>a</b></p></body></html>
<html><body><p>This is <b>a</b> paragraph</p></body></html>

答案 1 :(得分:2)

如果你添加文字......

my_tag = node.parent.setString(node.replace(match, "<myspan>"+match+"</myspan>"))

...再次通过BeautifulSoup传递

new_soup = BeautifulSoup(my_tag)

它应该被归类为BS标记对象并可用于解析。

您可以将这些更改应用于原始大量文本并将其作为一个整体运行,以避免重复。

编辑:

来自docs

# Here is a more complex example that replaces one tag with another: 

from BeautifulSoup import BeautifulSoup, Tag
soup = BeautifulSoup("<b>Argh!<a>Foo</a></b><i>Blah!</i>")
tag = Tag(soup, "newTag", [("id", 1)])
tag.insert(0, "Hooray!")
soup.a.replaceWith(tag)
print soup
# <b>Argh!<newTag id="1">Hooray!</newTag></b><i>Blah!</i>
相关问题