我使用Zillow的API并调用GetDeepComps
API。 API允许您在URL中包含地址,然后返回响应。
我想通过读取一个充满x地址的文本文件然后调用API x次来向API发送多个请求,直到文件中没有剩余地址为止。
变量formatted_addresses
的值应根据包含地址的文本文件中读取的行而改变。
我还想将地址及其相应的邮政编码存储在字典中。 这是我目前的代码。
def read_addresses_and_append_zip_codes():
f = open("addresses.txt", "r")
addresses = f.readlines()
addresses = [x.strip() for x in addresses]
print addresses
formatted_address = "2723+Green+Leaf+Way"
DEEP_SEARCH_RESULTS_BASE_URL = "http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=" + API_KEY + "&address=" + formatted_address + "&citystatezip=San%20Antonio%2C%20TX"
response = requests.get(DEEP_SEARCH_RESULTS_BASE_URL)
content = xmltodict.parse(response.content)
zip_code = content['SearchResults:searchresults']['response']['results']['result']['address']['zipcode']
print zip_code
read_addresses_and_append_zip_codes()
这是一个很好的方法吗?
答案 0 :(得分:1)
我会像这样定义一些基本网址
BASE_URL = "http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id={api_key}&address={encoded_addr}&citystatezip=San%20Antonio%2C%20TX"
然后,您可以使用API_KEY
这样插入formatted_address
和str.format()
new_url = BASE_URL.format(**{'api_key': API_KEY, 'encoded_addr': encoded_addr})
我们定义
import urllib
encoded_addr = urllib.quote_plus(addr)
然后整个事情看起来像这样:
def read_addresses_and_append_zip_codes():
zips = {}
BASE_URL = "http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id={0}&address={1}&citystatezip=San%20Antonio%2C%20TX"
with open("addresses.txt", "r") as f:
addresses = f.readlines()
addresses = [x.strip() for x in addresses]
# print addresses
for addr in addresses:
encoded_addr = urlparse.quote_plus(addr)
response = requests.get(BASE_URL.format(**{'api_key': API_KEY, 'encoded_addr': encoded_addr}))
content = xmltodict.parse(response.content)
zip_code = content['SearchResults:searchresults']['response']['results']['result']['address']['zipcode']
zips[addr] = zip_code
read_addresses_and_append_zip_codes()