从XML(Google距离矩阵API)中提取特定信息

Extract specific information from XML (Google Distance Matrix API)

这是我的 XML 输出:

<DistanceMatrixResponse>
<status>OK</status>
<origin_address>
868-978 Middle Tennessee Blvd, Murfreesboro, TN 37130, USA
</origin_address>
<destination_address>
980-1060 Middle Tennessee Blvd, Murfreesboro, TN 37130, USA
</destination_address>
<row>
<element>
<status>OK</status>
<duration>
<value>19</value>
<text>1 min</text>
</duration>
<distance>
<value>154</value>
<text>0.1 mi</text>
</distance>
</element>
</row>
</DistanceMatrixResponse>

我正在尝试使用 Python 从网络上将此 XML 保存到本地(这部分已完成)。保存文件后,我想提取 'duration' 值(在本例中为 19)和 'distance' 值(在本例中为 154)。

我似乎无法弄清楚如何从中读取和提取必要的信息 XML。我曾尝试使用 ElementTree 并尝试从 Whosebug 实施其他解决方案,但没有成功。我大约需要 3 个小时才能完成一个快速的过程。

这是我现在的代码:

import urllib2
import xml.etree.ElementTree as ET

## import XML and save it out
url = "https://maps.googleapis.com/maps/api/distancematrix/xml?units=imperial&origins=35.827581,-86.394077&destinations=35.827398,-86.392381&key=mygooglemapsAPIkey"
s = urllib2.urlopen(url)
contents = s.read()
file = open("export.xml", 'w')
file.write(contents)
file.close()
## finish saving the XML


element_tree = ET.parse("export.xml")
root = element_tree.getroot()
agreement = root.find("duration").text
print agreement


## open XML and save out travel time in seconds
xmlfile = 'export.xml'
element_tree = ET.parse(xmlfile)
root = element_tree.getroot()
agreement = root.findall("duration").text
print agreement

当前错误信息是:AttributeError: 'Nonetype' object has no attribute 'text'

我知道代码不完整,无法同时获取持续时间和距离,但此时我只是想让一些东西起作用!

只需使用XPath queries:

duration = tree.find('.//duration/value').text
distance = tree.find('.//distance/value').text

这是一个不错的 XPath 教程:http://zvon.org/comp/r/tut-XPath_1.html