修改tag的名称和属性
重命名一个tag,改变属性的值,添加或删除属性:
soup = BeautifulSoup(‘Extremely bold‘)
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 属性赋值,就相当于用当前的内容替代了原来的内容:
注意: 如果当前的tag包含了其它tag,那么给它的 .string 属性赋值会覆盖掉原有的所有内容包括子tag
append()
Tag.append() 方法想tag中添加内容,就好像Python的列表的 .append() 方法
NavigableString() 和 .new_tag()
如果想添加一段文本内容到文档中也没问题,可以调用Python的 append() 方法 或调用 NavigableString 的构造方法:
soup = BeautifulSoup(““)
tag = soup.b
tag.append(“Hello”)
new_string = NavigableString(” there”)
tag.append(new_string)
tag
# Hello there.
tag.contents
# [u’Hello’, u’ there’]
如果想要创建一段注释,或 NavigableString 的任何子类, 只要调用 NavigableS

本文详细介绍了如何使用BeautifulSoup4库修改HTML文档树,包括重命名tag、改变属性、添加或删除属性、修改.tag.string、使用.append()、.NavigableString()和.new_tag()、.insert()、.insert_before()和.insert_after()、.clear()、.extract()、.decompose()、.replace_with()、.wrap()以及.unwrap()等方法。
最低0.47元/天 解锁文章
476

被折叠的 条评论
为什么被折叠?



