多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 修改文档树 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.'] ```