`requests.get`对象,试图将`xml`解析为`pandas.DataFrame`

时间:2014-06-20 07:28:53

标签: python xml pandas

我已成功从Zillow's Get Region Children API创建了一个requests.get(url)对象,使用以下内容创建:

import requests

In [103]: socket = requests.get(''http://www.zillow.com/...neighborhood')

当我检查socket对象中的内容时,我会收到很多内容,我将在其中分享一些内容:

In [106]: socket.content
Out[106]: '<?xml version="1.0" encoding="utf-8"?><RegionChildren:regionchildren
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.zillow.com/static/xsd/RegionChildren.xsd 
http://www.zillowstatic.com/vstatic/479fdf9/static/xsd/RegionChildren.xsd"  
xmlns:RegionChildren="http://www.zillow.com/static/xsd/RegionChildren.xsd"><request>
<state>wa</state><city>seattle</city><childtype>neighborhood</childtype></request>
<message><text>Request successfully processed</text><code>0</code></message><response>
<region><id>16037</id><latitude>47.559364</latitude><longitude>-122.313752</longitude>
</region><subregiontype>neighborhood</subregiontype><list><count>107</count><region>
<id>250206</id><name>Capitol Hill</name><zindex currency="USD">398000</zindex>
<url>http://www.zillow.com/local-info/WA-Seattle/Capitol-Hill/r_250206/</url>...'

我去过xml.etree.ElementTree Tutorial Page,在那里他们说明了解析xml文件。看起来好像(根据文档),这应该是解析字符串的合适方法:

import lxml.etree.ElementTree as ET

In [107]: root = ET.fromstring(socket.content)

但是,我仍然无法使用提供的任何后续步骤访问任何标记元素(<zindex><name><region><id>等)教程,例如,我得到以下内容:

In [112]: root.tag
Out[112]: '{http://www.zillow.com/static/xsd/RegionChildren.xsd}regionchildren'

In [114]: for child in root:
          print child.tag, child.attrib
.....: 
request {}
message {}
response {}

我希望能够迭代所有不同的标记元素,将它们放入dictpandas.DataFrame,但我无法获得第一步实际访问元素。

1 个答案:

答案 0 :(得分:1)

最后,我能够使用BeautifulSoup获得所需的结果。具体如下:

第1步:

将数据加载到bs4对象,具体建议为where the parsing libraries are described

[In] 10: soup = bs4.BeautifulSoup(socket.content, ['lxml', 'xml'])

第2步:

看一下xml数据的混乱,以确定它的结构。

[In] 11: f = open('pretty_xml.xml', 'w')
[In] 12: f.writelines(soup.prettify())
[In] 13: f.close()

第3步:

开始提取

更仔细地查看数据后,使用bs4.findChildren()功能将每个节点提取到列表的单元格中。例如:

[In] 14: soup_list = soup.findChildren()

然后(假设tags对于每个列表元素都相同,或者与我的情况大致相似),使用text and name attributes of bs4.tag元素创建(index, values)配对,执行某些操作像这样:

[In] 15: d = {}
[In] 16: for i, element in enumerate(soup_list):
...:        index = map(lambda x: x.name, element.findChildren())
...:        vals = map(lambda x: unicode(x.text), element.findChildren())
...:        d[i] = pandas.Series(vals, index = index)

然后,您可以设置为pandas.DataFrame通过dict Series