相关疑难解决方法(0)

通过'ElementTree'在Python中解析带有命名空间的XML

我有以下XML,我想用Python解析ElementTree:

<rdf:RDF xml:base="http://dbpedia.org/ontology/"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:owl="http://www.w3.org/2002/07/owl#"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
    xmlns="http://dbpedia.org/ontology/">

    <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
        <rdfs:label xml:lang="en">basketball league</rdfs:label>
        <rdfs:comment xml:lang="en">
          a group of sports teams that compete against each other
          in Basketball
        </rdfs:comment>
    </owl:Class>

</rdf:RDF>
Run Code Online (Sandbox Code Playgroud)

我想找到所有owl:Class标签,然后提取其中所有rdfs:label实例的值.我使用以下代码:

tree = ET.parse("filename")
root = tree.getroot()
root.findall('owl:Class')
Run Code Online (Sandbox Code Playgroud)

由于命名空间,我收到以下错误.

SyntaxError: prefix 'owl' not found in prefix map
Run Code Online (Sandbox Code Playgroud)

我尝试在http://effbot.org/zone/element-namespaces.htm上阅读该文档,但由于上述XML具有多个嵌套命名空间,因此我仍然无法正常工作.

请告诉我如何更改代码以查找所有owl:Class标签.

python xml elementtree xml-namespaces xml-parsing

148
推荐指数
5
解决办法
12万
查看次数

ElementTree findall()返回空列表

我正在尝试编写一个与last.fm API进行交互的小脚本.

我有一些使用经验ElementTree,但我之前使用它的方式似乎不起作用,它返回一个空列表.
我删除了API密钥,因为我不确切知道它应该是多么私密,并举例说明了我收到的XML.

与API交互的类:

from xml.etree import ElementTree
import urllib
import urllib2

class Last_fmWrapper(object):
    def __init__(self):
        self.last_fm_api_key = '*****************************'
        self.api_url = 'http://ws.audioscrobbler.com/2.0/'
    def get_now_playing(self, last_fm_user, method):
        self.last_fm_user = last_fm_user
        self.method = method
        parameters = {'user':self.last_fm_user, 'api_key':self.last_fm_api_key, 'method':self.method}
        encoded_parameters = urllib.urlencode(parameters)
        request = urllib2.Request(self.api_url, encoded_parameters)
        response = urllib2.urlopen(request)
        api_results = ElementTree.parse(response).findall('track')
        # why does api_results == []?

    def compare_tasteometer(self):
        pass

    def register_user(self):
        pass
Run Code Online (Sandbox Code Playgroud)

调用get_now_playing方法Last_fmWrapper():

from last_fm_wrapper import Last_fmWrapper
last_fm = Last_fmWrapper()
now_playing = last_fm.get_now_playing('BiriBiriRG', 'user.getRecentTracks')
if …
Run Code Online (Sandbox Code Playgroud)

python xml elementtree last.fm

23
推荐指数
1
解决办法
3万
查看次数

标签 统计

elementtree ×2

python ×2

xml ×2

last.fm ×1

xml-namespaces ×1

xml-parsing ×1