# 修改文檔樹
Beautiful Soup的強項是文檔樹的搜索,但同時也可以方便的修改文檔樹
## 修改tag的名稱和屬性
在 [Attributes](#attributes) 的章節中已經介紹過這個功能,但是再看一遍也無妨. 重命名一個tag,改變屬性的值,添加或刪除屬性:
```
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
tag = soup.b
tag.name = "blockquote"
tag['class'] = 'verybold'
tag['id'] = 1
tag
# <blockquote class="verybold" id="1">Extremely bold</blockquote>
del tag['class']
del tag['id']
tag
# <blockquote>Extremely bold</blockquote>
```
## 修改 .string
給tag的 `.string` 屬性賦值,就相當于用當前的內容替代了原來的內容:
```
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)
tag = soup.a
tag.string = "New link text."
tag
# <a href="http://example.com/">New link text.</a>
```
注意: 如果當前的tag包含了其它tag,那么給它的 `.string` 屬性賦值會覆蓋掉原有的所有內容包括子tag
## append()
`Tag.append()` 方法想tag中添加內容,就好像Python的列表的 `.append()` 方法:
```
soup = BeautifulSoup("<a>Foo</a>")
soup.a.append("Bar")
soup
# <html><head></head><body><a>FooBar</a></body></html>
soup.a.contents
# [u'Foo', u'Bar']
```
## BeautifulSoup.new_string() 和 .new_tag()
如果想添加一段文本內容到文檔中也沒問題,可以調用Python的 `append()` 方法或調用工廠方法 `BeautifulSoup.new_string()` :
```
soup = BeautifulSoup("<b></b>")
tag = soup.b
tag.append("Hello")
new_string = soup.new_string(" there")
tag.append(new_string)
tag
# <b>Hello there.</b>
tag.contents
# [u'Hello', u' there']
```
如果想要創建一段注釋,或 `NavigableString` 的任何子類,將子類作為 `new_string()` 方法的第二個參數傳入:
```
from bs4 import Comment
new_comment = soup.new_string("Nice to see you.", Comment)
tag.append(new_comment)
tag
# <b>Hello there<!--Nice to see you.--></b>
tag.contents
# [u'Hello', u' there', u'Nice to see you.']
```