当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Python BeautifulSoup new_tag方法用法及代码示例

Beautiful Soup 的 new_tag(~) 方法创建一个新标签,然后我们可以将其插入到解析树中。

参数

1. tag name | string

标签的名称。

2. attribute | attribute | optional

新标签的属性。默认为 None

例子

考虑以下 HTML 文档:

my_html = """
       <div>
              <p>Alex</p>
              <p id="bob">Bob</p>
              <p>Cathy</p>
       </div>
"""
soup = BeautifulSoup(my_html)

标签名

要创建新标签:

# Create a new tag and initialise it's content
new_tag = soup.new_tag("p")
new_tag.string = "Eric"

要将其附加到现有的 "Bob" 标记:

bob_tag = soup.find("p", {"class": "Bob"})
bob_tag.append(new_tag)
print(soup.find("div"))



<div>
    <p id="alex">Alex</p>
    <p class="Bob">Bob<p>Eric</p></p>
    <p id="cathy">Cathy</p>
</div>

要在 "Bob" 标记之前插入新标记:

bob_tag = soup.find("p", {"class": "Bob"})
bob_tag.insert_before(new_tag)
print(soup.find("div"))



<div>
    <p id="alex">Alex</p>
    <p>Eric</p><p class="Bob">Bob</p>
    <p id="cathy">Cathy</p>
</div>

要在 "Bob" 标记后插入新标记:

bob_tag = soup.find("p", {"class": "Bob"})
bob_tag.insert_after(new_tag)
print(soup.find("div"))



<div>
    <p id="alex">Alex</p>
    <p class="Bob">Bob</p><p>Eric</p>
    <p id="cathy">Cathy</p>
</div>

属性

要创建具有 href 属性的新 "a" 标记:

# Create a new tag and initialise it's content
new_tag = soup.new_tag("a", href="http://www.skytowner.com")
new_tag.string = "Sky Towner"
print(new_tag)



<a href="http://www.skytowner.com">Sky Towner</a>

相关用法


注:本文由纯净天空筛选整理自Arthur Yanagisawa大神的英文原创作品 BeautifulSoup | new_tag method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。