Python用不寻常的标签名称解析XML(原子:链接)

问题描述:

我试图从下面的XML中解析出href。有多个workspace标签,下面我只是展示一个。Python用不寻常的标签名称解析XML(原子:链接)

myUrl = 'https://www.my-geoserver.com/geoserver/rest/workspaces' 
headers = {'Accept': 'text/xml'} 
resp = requests.get(myUrl,auth=('admin','password'),headers=headers) 

如果我搜索 '工作空间',我得到的对象返回:

<workspaces> 
    <workspace> 
    <name>practice</name> 
    <atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="https://www.my-geoserver.com/geoserver/rest/workspaces/practice.xml" type="application/xml"/> 
    </workspace> 
</workspaces> 

使用请求库以上来自于requests.get命令

lst = tree.findall('workspace') 
print(lst) 

导致:

[<Element 'workspace' at 0x039E70F0>, <Element 'workspace' at 0x039E71B0>, <Element 'workspace' at 0x039E7240>] 

那么好吧,但我如何获取文本HREF出字符串的,我曾尝试:

lst = tree.findall('atom') 
lst = tree.findall('atom:link') 
lst = tree.findall('workspace/atom:link') 

但他们没有工作,隔离标签,其实是最后一个创建错误

SyntaxError: prefix 'atom' not found in prefix map

如何获得带有这些标签名称的所有href实例?

对于其他人谁找到这个问题,冒号前的部分(在这种情况下​​)被称为一个名称空间,在这里引起的问题。解决方案很简单:

myUrl = 'https://www.my-geoserver.com/geoserver/rest/workspaces' 
headers = {'Accept': 'text/xml'} 
resp = requests.get(myUrl,auth=('admin','my_password'),headers=headers) 
stuff = resp.text 
to_parse=BeautifulSoup(stuff, "xml") 

for item in to_parse.find_all("atom:link"): 
    print(item) 

感谢萨基特米塔尔指出我朝着BeautifulSoup图书馆。关键是在BeautifulSoup函数中使用xml作为参数。使用lxml根本不会正确解析名称空间并忽略它们。

简单的解决方案,我发现:

>>> y=BeautifulSoup(x) 
>>> y 
<workspaces> 
<workspace> 
<name>practice</name> 
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="https://www.my-geoserver.com/geoserver/rest/workspaces/practice.xml" type="application/xml"> 
</atom:link></workspace> 
</workspaces> 
>>> c = y.workspaces.workspace.findAll("atom:link") 
>>> c 
[<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="https://www.my-geoserver.com/geoserver/rest/workspaces/practice.xml" type="application/xml"> 
</atom:link>] 
>>> 
+0

我得到简单的[]作为我的输出,它必须与resp.text的格式有关,它只是文本,据我所知。如果我使用y.workspaces.findAll(“workspace”),它会起作用,但那不是我所追求的。 –