Python利用Beautiful Soup模块修改内容方法示例


Posted in Python onMarch 27, 2017

前言

其实Beautiful Soup 模块除了能够搜索和导航之外,还能够修改 HTML/XML 文档的内容。这就意味着能够添加或删除标签、修改标签名称、改变标签属性值和修改文本内容等等。这篇文章非常详细的给大家介绍了Python利用Beautiful Soup模块修改内容的方法,下面话不多说,来看看详细的介绍吧。

修改标签

使用的示例 HTML 文档还是如下:

html_markup="""
 <div class="ecopyramid">
 <ul id="producers">
  <li class="producerlist">
  <div class="name">plants</div>
  <div class="number">100000</div>
  </li>
  <li class="producerlist">
  <div class="name">algae</div>
  <div class="number">100000</div>
  </li>
 </ul>
 </div>
 """

修改标签名称

soup = BeautifulSoup(html_markup,'lxml')
producer_entries = soup.ul
print producer_entries.name
producer_entries.name = "div"
print producer_entries.prettify()

修改标签属性值

# 修改标签属性
# 更新标签现有的属性值
producer_entries['id'] = "producers_new_value"
print producer_entries.prettify()
# 标签添加新的属性值
producer_entries['class'] = "newclass"
print producer_entries.prettify()
# 删除标签属性值
del producer_entries['class']
print producer_entries.prettify()

添加新的标签

我们可以使用 new_tag 方法来生成一个新的标签,然后使用 append() insert()insert_after()insert_before()方法来将标签添加到 HTML 树中。

例如在上述的 HTML 文档的 ul 标签中添加一个 li 标签 。首先要生成新的 li 标签,然后将其插入到 HTML 树结构中 。并在 li 标签中插入相应的 div 标签。

# 添加新的标签
# new_tag 生成一个 tag 对象
new_li_tag = soup.new_tag("li")
# 标签对象添加属性的方法
new_atag = soup.new_tag("a",href="www.example.com" rel="external nofollow" )
new_li_tag.attrs = {'class':'producerlist'}
soup = BeautifulSoup(html_markup,'lxml')
producer_entries = soup.ul
# 使用 append() 方法添加到末尾
producer_entries.append(new_li_tag)
print producer_entries.prettify()
# 生成两个 div 标签,将其插入到 li 标签中
new_div_name_tag = soup.new_tag("div")
new_div_name_tag['class'] = "name"
new_div_number_tag = soup.new_tag("div")
new_div_number_tag["class"] = "number"
# 使用 insert() 方法指定位置插入
new_li_tag.insert(0,new_div_name_tag)
new_li_tag.insert(1,new_div_number_tag)
print new_li_tag.prettify()

修改字符串内容

修改字符串内容可以使用 new_string()  、append()insert() 方法。

# 修改字符串内容
# 使用 .string 属性修改字符串内容
new_div_name_tag.string = 'new_div_name'
# 使用 .append() 方法添加字符串内容
new_div_name_tag.append("producer")
# 使用 soup 对象的 new_string() 方法生成字符串
new_string_toappend = soup.new_string("producer")
new_div_name_tag.append(new_string_toappend)
# 使用insert() 方法插入
new_string_toinsert = soup.new_string("10000")
new_div_number_tag.insert(0,new_string_toinsert)
print producer_entries.prettify()

删除标签节点

Beautiful Soup 模块提供了 decompose()extract() 方法来删除节点。

decompose() 方法删除节点,不仅会删除当前节点,还会把其子节点一块删除了。

extract() 方法用来从 HTML 树中删除节点或者字符串内容。

# 删除节点
third_producer = soup.find_all("li")[2]
# 使用 decompose() 方法删除 div 节点
div_name = third_producer.div
div_name.decompose()
print third_producer.prettify()
# 使用 extract() 方法删除节点
third_producer_removed = third_producer.extract()
print soup.prettify()

删除标签内容

标签可能有 NavigableString 对象或者 Tag 对象作为它的子节点,移除所有的这些子节点可以使用 clear() 方法。这将会移除标签的所有的 .content。

修改内容的其他方法

除了上面说到的方法,还有其他方法用来修改内容。

insert_after()insert_before() 方法

上面的两个方法能够在标签或者字符串的前面或者后面插入一个标签或者字符串。方法只能接收一个参数,要么是 NavigableString 对象要么是 Tag 对象。

replace_with() 方法

该方法是用一个新的标签或字符串内容替代原来的标签或者字符串,能够接收一个标签或者字符串作为输入。

wrap()unwrap() 方法

wrap() 方法是用另一个标签来包裹一个标签或者字符串。

unwrap() 方法则和 wrap() 方法相反。

# wrap()方法
li_tags = soup.find_all('li')
for li in li_tags:
 new_div_tag = soup.new_tag('div')
 li.wrap(new_div_tag)
print soup.prettify()
# unwrap()方法
li_tags = soup.find_all("li")
for li in li_tags:
 li.div.unwrap()
print soup.prettify()

总结

以上就是关于Python使用Beautiful Soup 模块修改内容的全部内容了,希望本文的内容对大家学习或者使用python能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Python 相关文章推荐
python中while循环语句用法简单实例
May 07 Python
Django1.7+python 2.78+pycharm配置mysql数据库
Oct 09 Python
Python实现读取并保存文件的类
May 11 Python
Python探索之修改Python搜索路径
Oct 25 Python
Python简单获取网卡名称及其IP地址的方法【基于psutil模块】
May 24 Python
TensorFlow实现卷积神经网络
May 24 Python
python3解析库pyquery的深入讲解
Jun 26 Python
python GUI库图形界面开发之PyQt5表单布局控件QFormLayout详细使用方法与实例
Mar 06 Python
python3中datetime库,time库以及pandas中的时间函数区别与详解
Apr 16 Python
python+requests接口自动化框架的实现
Aug 31 Python
python selenium xpath定位操作
Sep 01 Python
python 实现关联规则算法Apriori的示例
Sep 30 Python
python递归查询菜单并转换成json实例
Mar 27 #Python
Python中的命令行参数解析工具之docopt详解
Mar 27 #Python
Python使用PDFMiner解析PDF代码实例
Mar 27 #Python
详解python并发获取snmp信息及性能测试
Mar 27 #Python
使用Python写CUDA程序的方法
Mar 27 #Python
pyenv命令管理多个Python版本
Mar 26 #Python
Django实现自定义404,500页面教程
Mar 26 #Python
You might like
一个用于网络的工具函数库
2006/10/09 PHP
比较简单的百度网盘文件直链PHP代码
2013/03/24 PHP
使用PHP获取当前url路径的函数以及服务器变量
2013/06/29 PHP
[原创]php求圆周率的简单实现方法
2016/05/30 PHP
PHP实现链表的定义与反转功能示例
2018/06/09 PHP
windows 2008r2+php5.6.28环境搭建详细过程
2019/06/18 PHP
[HTML/CSS/Javascript]WWTJS
2007/09/25 Javascript
默认让页面的第一个控件选中的javascript代码
2009/12/26 Javascript
关于跨站脚本攻击问题
2011/12/22 Javascript
在服务端(Page.Write)调用自定义的JS方法详解
2013/08/09 Javascript
JS.elementGetStyle(element, style)应用示例
2013/09/24 Javascript
jquery实现先淡出再折叠收起的动画效果
2015/08/07 Javascript
概述javascript在Google IE中的调试技巧
2016/11/24 Javascript
详解使用vue-router进行页面切换时滚动条位置与滚动监听事件
2017/03/08 Javascript
详解vue父子组件间传值(props)
2017/06/29 Javascript
详解Vue2.0 事件派发与接收
2017/09/05 Javascript
详解webpack+ES6+Sass搭建多页面应用
2018/11/05 Javascript
vue 使用外部JS与调用原生API操作示例
2019/12/02 Javascript
JS使用Chrome浏览器实现调试线上代码
2020/07/23 Javascript
js回到页面指定位置的三种方式
2020/12/17 Javascript
Python实现同时兼容老版和新版Socket协议的一个简单WebSocket服务器
2014/06/04 Python
tensorflow 1.0用CNN进行图像分类
2018/04/15 Python
python爬取网页内容转换为PDF文件
2020/07/28 Python
python 的 scapy库,实现网卡收发包的例子
2019/07/23 Python
Python 写了个新型冠状病毒疫情传播模拟程序
2020/02/14 Python
python GUI框架pyqt5 对图片进行流式布局的方法(瀑布流flowlayout)
2020/03/12 Python
Django静态文件加载失败解决方案
2020/08/26 Python
image-set实现Retina屏幕下图片显示详细介绍
2012/12/24 HTML / CSS
Paul Smith英国官网:英国国宝级时装品牌
2019/03/21 全球购物
澳大利亚在线高跟鞋商店:Shoe Me
2019/11/19 全球购物
仓库管理专业个人自我评价范文
2013/11/11 职场文书
校园活动宣传方案
2014/03/28 职场文书
2016年秋季运动会加油稿
2015/12/21 职场文书
教师实习自我鉴定总结
2019/08/20 职场文书
python中如何对多变量连续赋值
2021/06/03 Python
教你快速构建一个基于nginx的web集群项目
2021/11/27 Servers