在Python中访问OrderedDict的特定元素

2024-06-11 15:13:54 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码调用Zillow的API并以XML形式返回响应。我将XML转换成字典,但是在访问特定元素时遇到了一个问题。如何在响应中创建包含“zpid”值的变量?在

我的代码是:

import requests
import xmltodict, json
import collections
API_KEY = "KEY_HIDDEN_FOR_SECURITY_REASONS"
DEEP_COMP_BASE_URL = "http://www.zillow.com/webservice/GetDeepComps.htm?zws-id=" + API_KEY +"&zpid=48749425&count=5"
DEEP_SEARCH_RESULTS_BASE_URL = "http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=" + API_KEY +  "&address=2114+Bigelow+Ave&citystatezip=Seattle%2C+WA"

def organize_json(json_thing, sort=True, indents=4):
    if type(json_thing) is str:
        print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
    else:
        print(json.dumps(json_thing, sort_keys=sort, indent=indents))
    return None


def get_deep_comps():
    response = requests.get(DEEP_COMP_BASE_URL)
    content = xmltodict.parse(response.content)
    print content

def get_zpid_from_address():
    print("Finding address...")


get_deep_comps()

以及输出:

^{pr2}$

在Python中有什么简洁的方法来处理这个问题?在


Tags: keyimportapijsonurlbasegetaddress
1条回答
网友
1楼 · 发布于 2024-06-11 15:13:54

我尝试了你的代码,得到了这个xml作为响应内容

<?xml version="1.0" encoding="utf-8"?>
<Comps:comps xsi:schemaLocation="http://www.zillow.com/static/xsd/Comps.xsd https://www.zillowstatic.com/vstatic/6ce354c/static/xsd/Comps.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:Comps="http://www.zillow.com/static/xsd/Comps.xsd">
    <request>
       <zpid></zpid>
       <count></count>
    </request>
    <message>
        <text>Error: invalid or missing ZWSID parameter</text>
        <code>2</code>
    </message>
</Comps:comps>

这就产生了下面的有序dict

^{pr2}$

要获得zipid的值,在我的示例中它只是none,您可以使用以下行

zpid=content['Comps:comps']['request']['zpid']

相关问题 更多 >