Python : Beautiful Soup修改文档树

本文详细介绍了Beautiful Soup库如何修改HTML文档树,包括更改tag名称、属性、内容,以及添加、删除和操作tag。此外,还讨论了如`append()`、`insert()`、`replace_with()`等方法,以及文本内容的处理、输出格式和编码问题。通过实例展示了各种操作,帮助读者理解Beautiful Soup在文档处理中的强大功能。
摘要由CSDN通过智能技术生成

修改文档树
Beautiful Soup的强项是文档树的搜索,但同时也可以方便的修改文档树

修改tag的名称和属性
在 Attributes 的章节中已经介绍过这个功能,但是再看一遍也无妨. 重命名一个tag,改变属性的值,添加或删除属性:

soup = BeautifulSoup(‘Extremely bold’)
tag = soup.b

tag.name = “blockquote”
tag[‘class’] = ‘verybold’
tag[‘id’] = 1
tag

Extremely bold

del tag[‘class’]
del tag[‘id’]
tag

Extremely bold

修改 .string
给tag的 .string 属性赋值,就相当于用当前的内容替代了原来的内容:

markup = ‘I linked to example.com
soup = BeautifulSoup(markup)

tag = soup.a
tag.string = “New link text.”
tag

New link text.

注意: 如果当前的tag包含了其它tag,那么给它的 .string 属性赋值会覆盖掉原有的所有内容包括子tag

append()
Tag.append() 方法想tag中添加内容,就好像Python的列表的 .append() 方法:

soup = BeautifulSoup(“Foo”)
soup.a.append(“Bar”)

soup

FooBar

soup.a.contents

[u’Foo’, u’Bar’]

BeautifulSoup.new_string() 和 .new_tag()
如果想添加一段文本内容到文档中也没问题,可以调用Python的 append() 方法或调用工厂方法 BeautifulSoup.new_string() :

soup = BeautifulSoup("")
tag = soup.b
tag.append(“Hello”)
new_string = soup.new_string(" there")
tag.append(new_string)
tag

Hello there.

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

Hello there

tag.contents

[u’Hello’, u’ there’, u’Nice to see you.’]

这是Beautiful Soup 4.2.1 中新增的方法

创建一个tag最好的方法是调用工厂方法 BeautifulSoup.new_tag() :

soup = BeautifulSoup("")
original_tag = soup.b

new_tag = soup.new_tag(“a”, href=“http://www.example.com”)
original_tag.append(new_tag)
original_tag

new_tag.string = “Link text.”
original_tag

Link text.

第一个参数作为tag的name,是必填,其它参数选填

insert()
Tag.insert() 方法与 Tag.append() 方法类似,区别是不会把新元素添加到父节点 .contents 属性的最后,而是把元素插入到指定的位置.与Python列表总的 .insert() 方法的用法下同:

markup = ‘I linked to example.com
soup = BeautifulSoup(markup)
tag = soup.a

tag.insert(1, "but did not endorse ")
tag

I linked to but did not endorse example.com

tag.contents

[u’I linked to ‘, u’but did not endorse’, example.com]

insert_before() 和 insert_after()
insert_before() 方法在当前tag或文本节点前插入内容:

soup = BeautifulSoup(“stop”)
tag = soup.new_tag(“i”)
tag.string = “Don’t”
soup.b.string.insert_before(tag)
soup.b

Don’tstop

insert_after() 方法在当前tag或文本节点后插入内容:

soup.b.i.insert_after(soup.new_string(" ever "))
soup.b

Don’t ever stop

soup.b.contents

[Don’t, u’ ever ‘, u’stop’]

clear()
Tag.clear() 方法移除当前tag的内容:

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值