BeautifulSoup操作xml文件

BeautifulSoup操作html的介绍较为常见,可参考官方文档,常见的对xml的操作可以使用ElementTree进行操作,这里并不是介绍BeautifulSoup操作xml,对自己在一次实践中遇到的问题进行记录。


问题:操作XML后,其中有多个结点,这里姑且以Id结点为例,需要替换一个其中一个Id结点,该Id结点可以通过父节点区分其他结点,因为ElementTree中可以使用iter()进行遍历,可以很方边的找到Id结点,但是我不知道如何找寻其父节点,最后想使用BeautifulSoup(),如果大家有什么方法,还望不吝赐教


<?xml version='1.0' encoding='UTF-8'?>
<nvd  xmlns="namesapce test">
<data>
    <xtrn>
        <Id>2019</Id>
    </xtrn>
    <country name="Liechtenstein">
        <rank>1</rank>
        <Id>2008</Id>
        <gdppc>141100</gdppc>
            <tag>temp</tag>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="中国">
        <rank>68</rank>
        <Id>2011</Id>
        <gdppc>13600</gdppc>
        <neighbor name="赵三" direction="西边"/>
        <neighbor name="李四" direction="东北"/>
        <temp information="bs4">bs4study</temp>
    </country>
</data>
</nvd>

BeautifulSoup文档中介绍解析xml文件的方法如下:

BeautifulSoup(markup, "xml")

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种: Tag , NavigableString , BeautifulSoup , Comment.

1.Tag结点

Tag 对象与XML或HTML原生文档中的tag相同:

#-*-encoding:utf-8-*-
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("websit.xml"),'xml')
#打印文件对象信息
# print(soup)
#打印tag结点
print(soup.tag)
print(type(soup.tag))

在原文件中查找确实有“tag”结点,因此这里使用结点的时候可以直接使用文件对象.标签的形式进行索引。

那文件对象两个最重要的属性就是name和attributes,对于大多数对于xml实际操作中,均是对标签的属性和name进行操作。

#-*-encoding:utf-8-*-
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("websit.xml"),'xml')

print("temp(tag):",soup.temp)
print("temp(tag)name:",soup.temp.name)
print("temp(tag)attribute:",soup.temp.attrs)
#可以通过键值的形式查找
print("temp(tag)attribute:",soup.temp['information'])

注意tag标签的属性可以被添加,删除或修改. 再说一次, tag的属性操作方法与字典一样

1.1 attibute

#替换属性值
for index in soup.find_all("temp"):
    print type(index.attrs)
    if index.attrs.has_key("information"):
        index.attrs.update({"information":"8520"})

如果查找temp标签,想要替换其attribute属性,由于index.attrs为字典,可以通过键值的形式进行操作

1.2 name

字符串常被包含在tag内.Beautiful Soup用 NavigableString 类来包装tag中的字符串,tag中包含的字符串不能编辑,但是可以被替换成其它的字符串,用 replace_with() 方法:

xml中有三个Id标签,但是只想替换其父节点为xtrn的结点的name值,使用replace_with

for index  in soup.find_all('Id'):
    #替换name值,只能使用replace_with
    if index.parent.name == "xtrn":
        print(index.text)
        index.string.replace_with("2020")

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值