修改html树无非是对其中标签的改动, 改动标签的名字(也就是类型), 属性和标签里的内容... 先讲这边提供了很方便的方法来对其进行改动...

 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>

然后是改动内容 :

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>

当然你还可以用append(), 我让我奇怪的是使用append()之后的效果看上去是一样的, 但是调用.contents却会发现其实append()是在.contents代表的那个list中append. 另一方面, 你还可以用一个 NavigableString替代String, 也是一样的.

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'] soup = BeautifulSoup("<b></b>")
tag = soup.b
tag.append("Hello")
new_string = NavigableString(" there")
tag.append(new_string)
tag
# <b>Hello there.</b>
tag.contents
# [u'Hello', u' there']

当然你还可以用append()在tag内部添加注释 :

from bs4 import Comment
new_comment = Comment("Nice to see you.")
tag.append(new_comment)
tag
# <b>Hello there<!--Nice to see you.--></b>
tag.contents
# [u'Hello', u' there', u'Nice to see you.']

你甚至可以直接创建一个新的tag, 对于new_tag(), 它只有第一个参数是必须的 :

soup = BeautifulSoup("<b></b>")
original_tag = soup.b new_tag = soup.new_tag("a", href="http://www.example.com")
original_tag.append(new_tag)
original_tag
# <b><a href="http://www.example.com"></a></b> new_tag.string = "Link text."
original_tag
# <b><a href="http://www.example.com">Link text.</a></b>

除了append()还有insert(), 它的插入, 从原理上来看也是插入了.contents 返回的那个list.

markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)
tag = soup.a tag.insert(1, "but did not endorse ")
tag
# <a href="http://example.com/">I linked to but did not endorse <i>example.com</i></a>
tag.contents
# [u'I linked to ', u'but did not endorse', <i>example.com</i>]

有关insert还有insert_before()和insert_after(), 就是插在当前调用tag的前面和后面.

soup = BeautifulSoup("<b>stop</b>")
tag = soup.new_tag("i")
tag.string = "Don't"
soup.b.string.insert_before(tag)
soup.b
# <b><i>Don't</i>stop</b> soup.b.i.insert_after(soup.new_string(" ever "))
soup.b
# <b><i>Don't</i> ever stop</b>
soup.b.contents
# [<i>Don't</i>, u' ever ', u'stop']

clear()很简单, 就是把所调用标签的内容全部清除.

markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)
tag = soup.a tag.clear()
tag
# <a href="http://example.com/"></a>

比clear()更神奇的是另外一个extract(),  extract()能够讲所调用的tag从html树中抽出, 同时返回提取的tag, 此时原来html树的该tag被删除.

markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)
a_tag = soup.a i_tag = soup.i.extract() a_tag
# <a href="http://example.com/">I linked to</a> i_tag
# <i>example.com</i> print(i_tag.parent)
None

decompose()和extract()的区别就在于它完全毁掉所调用标签, 而不返回(这里要注意remove()是毁掉所调用标签的内容...).

markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)
a_tag = soup.a soup.i.decompose() a_tag
# <a href="http://example.com/">I linked to</a>

replace_with()能够将其调用标签调换成参数标签, 同时返回调用标签...(相当于比extract()多了一个insert()的步骤)

markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)
a_tag = soup.a new_tag = soup.new_tag("b")
new_tag.string = "example.net"
a_tag.i.replace_with(new_tag) a_tag
# <a href="http://example.com/">I linked to <b>example.net</b></a>

还有wrap()和unwrap(), 好像是用参数标签包住调用标签, 而unwrap()则用调用标签的内容替代调用标签本身.

 soup = BeautifulSoup("<p>I wish I was bold.</p>")
soup.p.string.wrap(soup.new_tag("b"))
# <b>I wish I was bold.</b> soup.p.wrap(soup.new_tag("div")
# <div><p><b>I wish I was bold.</b></p></div> markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)
a_tag = soup.a a_tag.i.unwrap()
a_tag
# <a href="http://example.com/">I linked to example.com</a>

读BeautifulSoup官方文档之html树的修改的更多相关文章

  1. 读BeautifulSoup官方文档之html树的打印

    prettify()能返回一个格式良好的html的Unicode字符串 : markup = '<a href="http://example.com/">I link ...

  2. 读BeautifulSoup官方文档之html树的搜索(1)

    之前介绍了有关的四个对象以及他们的属性, 但是一般情况下要在杂乱的html中提取我们所需的tag(tag中包含的信息)是比较复杂的, 现在我们可以来看看到底有些什么搜索的方法. 最主要的两个方法当然是 ...

  3. 读BeautifulSoup官方文档之html树的搜索(2)

    除了find()和find_all(), 这里还提供了许多类似的方法我就细讲了, 参数和用法都差不多, 最后四个是next, previous是以.next/previous_element()来说的 ...

  4. 读BeautifulSoup官方文档之与bs有关的对象和属性(1)

    自从10号又是5天没更, 是, 我再一次断更... 原因是朋友在搞python, 老问我问题, 我python也是很久没碰了, 于是为了解决他的问题, 我只能重新开始研究python, 为了快速找回感 ...

  5. 读BeautifulSoup官方文档之与bs有关的对象和属性(2)

    上一节说到tag, 这里接着讲, tag有个属性叫做string, tag.string其实就是我们要掌握的四个对象中的第二个 ---- NavigableString,  它代表的是该tag内的te ...

  6. 读BeautifulSoup官方文档之与bs有关的对象和属性(3)

    上一节说到.string的条件很苛刻, 如果某个tag里面包含了超过一个children, 就会返回None, 但是这里提供另外一种方式 .strings, 它返回的是一个generator, 比如对 ...

  7. 读vue-cli3 官方文档的一些学习记录

    原来一直以为vue@cli3 就是创建模板的工具,读了官方文档才知道原来这么有用,不少配置让我长见识了 Prefetch 懒加载配置 懒加载相信大家都是知道的,使用Import() 语法就可以在需要的 ...

  8. Beautifulsoup官方文档

    Beautiful Soup 中文文档 原文 by Leonard Richardson (leonardr@segfault.org) 翻译 by Richie Yan (richieyan@gma ...

  9. 读jQuery官方文档:$(document).ready()与避免冲突

    $(document).ready() 通常你想在DOM结构加载完毕之后才执行相关脚本.使用原生JavaScript,你可能调用window.onload = function() { ... }, ...

随机推荐

  1. Http请求工具类(Java原生Form+Json)

    package com.tzx.cc.common.constant.util; import java.io.IOException; import java.io.InputStream; imp ...

  2. 注册表 Run、RunOnce 浅析

    绝大多数使用过 Windows 操作系统的用户都不会对注册表的 Run.RunOnce 键值感到陌生,但你真的了解所有这些键值的细节吗?让我们具体说来. 本文在Win2000,WinXp.Vista. ...

  3. windows下的定时任务设置详解

    windows下的定时任务设置详解 一.总结 一句话总结: 1.php.exe是什么? 就是php中自带的一个exe,不是我们写的,这个exe是可以执行其他的PHP的 二.windows下的定时任务设 ...

  4. Redis的增删改查、持久化你会了吗

    原文:Redis的增删改查.持久化你会了吗 Redis是用C语言实现的,一般来说C语言实现的程序"距离"操作系统更近,执行速度相对会更快. Redis使用了单线程架构,预防了多线程 ...

  5. Linux下新手怎样将VIM配置成C++编程环境(能够STL自己主动补全)

    ~ 弄拉老半天,最终弄的几乎相同啦,果然程序猿还是须要有点折腾精神啊. 首先你要安装vim,命令:sudo apt-get install vim vim它仅仅是一个编辑器,它不是IDE(比方code ...

  6. DAX的圈圈大坑:循环依赖关系错误circular dependency (单表篇)

    使用DAX中的某些函数特别类似Calculate这种函数创建计算列时很容易出现一种错误,叫做检测到循环依赖关系,即:A circular dependency was detected.对于刚接触Da ...

  7. Lettcode_104_Maximum Depth of Binary Tree

    本文研究的总结,欢迎转载,但请注明出处:http://blog.csdn.net/pistolove/article/details/41964475 Maximum Depth of Binary ...

  8. webpack单独构建scss文件与.vue组件里构建scss的一个坑

    在入口main.js里构建scss是通过引入模块的方式 import './assets/_reset.scss'; import './assets/_flex.scss'; import './a ...

  9. Python 图像处理: 生成二维高斯分布蒙版

    在图像处理以及图像特效中,经常会用到一种成高斯分布的蒙版,蒙版可以用来做图像融合,将不同内容的两张图像结合蒙版,可以营造不同的艺术效果. I=M∗F+(1−M)∗B 这里I 表示合成后的图像,F 表示 ...

  10. C#中的反射总结

      = 导航   顶部 什么是反射 为什么要使用反射 C#反射相关的命名空间 通过反射创建类型的实例 通过反射调用类的方法 查看类中成员 查看类的构造函数 查看类中属性 查看类中字段 反射实现的接口 ...