當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。