Python BeautifulSoup XML 解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4071696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:07:11  来源:igfitidea点击:

Python BeautifulSoup XML Parsing

pythonxmlparsingbeautifulsoup

提问by Caley Woods

I've written a simple script to parse XML chat logs using the BeautifulSoup module. The standard soup.prettify() works ok except chat logs have a lot of fluff in them. You can see both the script code and some of the XML input file I'm working with below:

我编写了一个简单的脚本来使用 BeautifulSoup 模块解析 XML 聊天日志。标准的soup.prettify() 工作正常,除了聊天记录中有很多绒毛。您可以在下面看到我正在使用的脚本代码和一些 XML 输入文件:

Code

代码

import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
    file = sys.argv[1]
    handler = open(file).read()
    soup = Soup(handler)
    print soup.prettify()

if __name__ == "__main__":
    parseLog(sys.argv[1])

Test XML Input

测试 XML 输入

<?xml version="1.0"?>
<?xml-stylesheet type='text/xsl' href='MessageLog.xsl'?>
<Log FirstSessionID="1" LastSessionID="2"><Message Date="10/31/2010" Time="3:43:48 PM"     DateTime="2010-10-31T20:43:48.937Z" SessionID="1"><From><User FriendlyName="Jon"/></From>    <To><User FriendlyName="Bill"/></To><Text Style="font-family:Segoe UI; color:#000000; ">hey, what's up?</Text></Message>
<Message Date="10/31/2010" Time="3:44:03 PM" DateTime="2010-10-15T20:44:03.421Z" SessionID="1"><From><User FriendlyName="Jon"/></From><To><User FriendlyName="Bill"/></To><Text Style="font-family:Segoe UI; color:#000000; ">Got your message</Text></Message> 
<Message Date="10/31/2010" Time="3:44:31 PM" DateTime="2010-10-15T20:44:31.390Z" SessionID="2"><From><User FriendlyName="Bill"/></From><To><User FriendlyName="Jon"/></To><Text Style="font-family:Segoe UI; color:#000000; ">oh, great</Text></Message>
<Message Date="10/31/2010" Time="3:44:59 PM" DateTime="2010-10-15T20:44:59.281Z" SessionID="2"><From><User FriendlyName="Bill"/></From><To><User FriendlyName="Jon"/></To><Text Style="font-family:Segoe UI; color:#000000; ">hey, i gotta run</Text></Message>

I'm wanting to be able to output this into a format like the following or at least something that is more readable than pure XML:

我希望能够将其输出为如下格式或至少比纯 XML 更具可读性的格式:

Jon: Hey, what's up? [10/31/10 @ 3:43p]

乔恩:嘿,怎么了?[10/31/10 @ 3:43p]

Jon: Got your message [10/31/10 @ 3:44p]

乔恩:收到你的消息 [10/31/10 @ 3:44p]

Bill: oh, great [10/31/10 @ 3:44p]

比尔:哦,太好了 [10/31/10 @ 3:44p]

etc.. I've heard some decent things about the PyParsing module, maybe it's time to give it a shot.

等等。我听说过一些关于 PyParsing 模块的好消息,也许是时候试一试了。

采纳答案by dcolish

BeautifulSoup makes getting at attributes and values in xml really simple. I tweaked your example function to use these features.

BeautifulSoup 使获取 xml 中的属性和值变得非常简单。我调整了您的示例函数以使用这些功能。

import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
    file = sys.argv[1]
    handler = open(file).read()
    soup = Soup(handler)
    for message in soup.findAll('message'):
        msg_attrs = dict(message.attrs)
        f_user = message.find('from').user
        f_user_dict = dict(f_user.attrs)
        print "%s: %s [%s @ %s]" % (f_user_dict[u'friendlyname'],
                                    message.find('text').decodeContents(),
                                    msg_attrs[u'date'],
                                    msg_attrs[u'time'])


if __name__ == "__main__":
    parseLog(sys.argv[1])

回答by Binary Phile

I'd recommend using the builtin ElementTreemodule. BeautifulSoup is meant to handle unwell-formed code like hacked up HTML, whereas XML is well-formed and meant to be read by an XML library.

我建议使用内置的ElementTree模块。BeautifulSoup 旨在处理格式不正确的代码,如修改后的 HTML,而 XML 格式良好,旨在由 XML 库读取。

Update: some of my recent reading here suggests lxml as a library built on and enhancing the standard ElementTree.

更新:我最近在此处阅读的一些文章建议将 lxml 作为构建在标准 ElementTree 上并对其进行增强的库。