我想解析RankByCountry中的国家代码属性。我该怎么做呢?
意思是-打印一个列表'GB','US','O‘
<aws:UrlInfoResponse xmlns:aws="http://alexa.amazonaws.com/doc/2005-10-05/"><aws:Response xmlns:aws="http://awis.amazonaws.com/doc/2005-07-11"><aws:OperationRequest><aws:RequestId>122bfdc6-ae8e-d2a2-580e-3841ab33b966</aws:RequestId></aws:OperationRequest><aws:UrlInfoResult><aws:Alexa>
<aws:TrafficData>
<aws:DataUrl type="canonical">androidjones.com/</aws:DataUrl>
<aws:RankByCountry>
<aws:Country Code="GB">
<aws:Rank>80725</aws:Rank>
<aws:Contribution>
<aws:PageViews>30.6%</aws:PageViews>
<aws:Users>41.3%</aws:Users>
</aws:Contribution>
</aws:Country>
<aws:Country Code="US">
<aws:Rank>354356</aws:Rank>
<aws:Contribution>
<aws:PageViews>39.1%</aws:PageViews>
<aws:Users>28.9%</aws:Users>
</aws:Contribution>
</aws:Country>
<aws:Country Code="O">
<aws:Rank/>
<aws:Contribution>
<aws:PageViews>30.2%</aws:PageViews>
<aws:Users>29.8%</aws:Users>
</aws:Contribution>
</aws:Country>
</aws:RankByCountry>
</aws:TrafficData>
</aws:Alexa></aws:UrlInfoResult><aws:ResponseStatus xmlns:aws="http://alexa.amazonaws.com/doc/2005-10-05/"><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:UrlInfoResponse>已经试过了--
namespaces = {"aws": "http://awis.amazonaws.com/doc/2005-07-11"}
RankByCountry = tree.xpath("//aws:Country/Code", namespaces=namespaces)但没有运气。
还包括:
for country in tree.xpath('//Country'):
for attrib in country.attrib:
print '@' + attrib + '=' + country.attrib[attrib]发布于 2015-07-06 13:27:10
文档看起来很奇怪,因为它两次使用aws名称空间前缀。您需要使用更具体的命名空间,因为这会用前缀aws覆盖全局命名空间。其实你这样做是对的。
问题在于xpath表达式本身,它应该如下所示:
for country in tree.xpath('//aws:RankByCountry/aws:Country/@Code', namespaces=namespaces):
print(country) 注意,<aws:RankByCountry>没有Code属性,但是<aws:Country>有。
https://stackoverflow.com/questions/31246537
复制相似问题