【问题标题】:Python BeautifulSoup - Add Tags around found keywordPython BeautifulSoup - 在找到的关键字周围添加标签
【发布时间】:2013-01-17 03:26:48
【问题描述】:

我目前正在从事一个项目,我希望在该项目中允许在大量 HTML 文件中/上进行正则表达式搜索。

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

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

但是,我还想在我找到的关键字周围添加我自己的 -标签。

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

# 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>"))

这样我只添加文本而不是适当的标签,因为文档不是新解析的,我希望避免这种情况!

我希望我的问题变得有点清楚:)

【问题讨论】:

    标签: python html insert tags beautifulsoup


    【解决方案1】:

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

    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>
    

    【讨论】:

    • 这不是我最终做的,但它接近我的想法!所以我接受了这个答案,因为它解决了问题!我要改变我的实现。不知道我可以将文本和标签附加到节点:) 谢谢!
    【解决方案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>
    

    【讨论】:

    猜你喜欢
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    相关资源
    最近更新 更多