【问题标题】:Removing a tag and its contents in xml using BeautifulSoup and lxml in Python在 Python 中使用 BeautifulSoup 和 lxml 在 xml 中删除标签及其内容
【发布时间】:2013-12-07 00:10:06
【问题描述】:

我正在处理我的 Evernote 数据 - 提取到一个 xml 文件。我已经使用 BeautifulSoup 解析了数据,这里是我的 xml 数据的一个样本。

<note>
<title>
 Audio and camera roll from STUDY DAY! in San Francisco
</title>
<content>
<![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
<en-note><div><en-media type="image/jpeg" hash="e3a84de41c9886b93a6921413b8482d5" width="1080" style="" height="1920"/><en-media type="image/jpeg" hash="b907b22a9f2db379aec3739d65ce62db" width="1123" style="" height="1600"/><en-media type="audio/wav" hash="d3fdcd5a487531dc156a8c5ef6000764" style=""/><br/></div>

</en-note>
]]>
</content>
<created>
 20130217T153800Z
</created>
<updated>
 20130217T154311Z
</updated>
<note-attributes>
<latitude>
 37.78670730072799
</latitude>
<longitude>
 -122.4171893858559
</longitude>
<altitude>
 42
</altitude>
<source>
 mobile.iphone
</source>
<reminder-order>
 0
</reminder-order>
</note-attributes>
<resource>
<data encoding="base64">

我想在这里探索两种途径: 1.查找和删除特定标签(在这种情况下) 2. 定位一组/标签列表以提取到另一个文档

这是我当前的代码,它解析 xml 并对其进行美化并输出到文本文件。

from bs4 import BeautifulSoup
soup = BeautifulSoup(open('myNotes.xml','r'))
with open("file.txt", "w") as f:
f.write(soup.prettify().encode('utf8'))

【问题讨论】:

    标签: python xml parsing beautifulsoup lxml


    【解决方案1】:

    您可以按名称搜索节点

    from BeautifulSoup import BeautifulSoup
    soup = BeautifulSoup(open('myNotes.xml', 'r'))
    
    
    source = soup.source
    print source
    
    #<source>
    # mobile.iphone
    #</source>
    
    
    source = soup.source
    print source.string
    
    # mobile.iphone
    

    另一种方法,findAll方法:

    for tag in soup.findAll('source'):
        print tag.string
    

    如果你想打印每个节点剥离标签,这应该可以完成工作:

    for tag in soup.findAll():
        print tag.string
    

    希望对你有帮助。

    编辑:________

    BeautifulSoup 假设您知道结构,尽管根据定义 xml 是结构化数据存储。 所以你需要给 BS 一个指导来解析你的 xml。

    row = []
    title = soup.note.title.string
    created = soup.note.created.string
    row.append(title)
    row.append(created)
    

    现在您只需遍历 xml。

    【讨论】:

    • 如果我想打印嵌套的元素,我该怎么做? - 例如,将(标题、创建、更新、纬度、经度、mime、时间戳和文件名)的每次出现打印为一行,每个类别作为一列。
    • BeautifulSoup 假设您知道结构,尽管根据定义 xml 是结构化数据存储。所以你需要给BS一个指导来解析你的xml。有关详细信息,请参阅编辑。
    【解决方案2】:

    如果您使用BeautifulSoup,您可以使用getText() 方法去除子元素中的标签并得到一个合并文本

    source.getText()
    

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 2013-06-01
      • 2019-05-11
      • 2021-01-28
      • 2021-11-04
      • 1970-01-01
      相关资源
      最近更新 更多