首页 > 编程 > Python > 正文

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

2020-02-23 04:29:37
字体:
来源:转载
供稿:网友

前言

其实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.ulprint producer_entries.nameproducer_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()            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表