如何通过Census Geocoder API获取经纬度?Python新手求助
问题描述
我从未使用过Python或调用过API,现在有点懵。我需要把地址发送到人口普查局的地理编码API来获取对应的纬度和经度,但找到的教程全是关于批量处理(addressbatch)的,我不需要批量功能。我的地址是从命令行传入的随机地址,下面是我写的跑不起来的代码,请问怎么让这个API返回经纬度?
import sys import socket import subprocess import requests import json def main(): # 读取命令行传入的URL urlIn = sys.argv[1] IP = socket.gethostbyname(urlIn) res = subprocess.getstatusoutput("whois " + IP) ressplit = res[1].split("\n") # 从whois结果中解析地址 for i in ressplit: if i.startswith("Address: "): a = i[10:] if i.startswith("City: "): c = i[6:] if i.startswith("StateProv: "): s = i[11:] if i.startswith("PostalCode: "): p = i[12:] break # 拼接完整地址 address = a.strip() + ", " + c.strip() + ", " + s.strip() + " " + p.strip() print(address) # 地理编码API基础地址 geo_s = "https://geocoding.geo.census.gov/geocoder/locations/address?" location = address PARAMS = {'address':location} response = requests.get(url = geo_s, params = PARAMS) data = response.json() # 重复解析JSON(冗余) geojs = json.loads(response.text) latitude = data['x'] longitude = data ['y'] if __name__ == "__main__": main()
终端运行报错
cscd330lab2 % ./lab2.py "youtube.com" 1600 Amphitheatre Parkway, Mountain View, CA 94043 Traceback (most recent call last): File "/Users/emilyherbert/Library/Python/3.9/lib/python/site-packages/requests/models.py", line 971, in json return complexjson.loads(self.text, **kwargs) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 346, in loads return _default_decoder.decode(s) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/emilyherbert/Desktop/cscd330lab2/./lab2.py", line 82, in <module> main() File "/Users/emilyherbert/Desktop/cscd330lab2/./lab2.py", line 40, in main data = response.json() File "/Users/emilyherbert/Library/Python/3.9/lib/python/site-packages/requests/models.py", line 975, in json raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
解决步骤
补全API必填参数
人口普查局的地理编码API默认返回XML格式,必须显式指定返回JSON,同时还要提供benchmark参数(指定地理数据版本,常用Public_AR_Current)。修改请求参数:PARAMS = { 'address': location, 'format': 'json', 'benchmark': 'Public_AR_Current' }修正JSON解析逻辑
API返回的坐标不是直接在根节点,而是嵌套在result->addressMatches[0]->coordinates下,而且注意API里x是经度,y是纬度。替换解析代码:response = requests.get(url=geo_s, params=PARAMS) data = response.json() # 检查是否有匹配结果 if data['result']['addressMatches']: coords = data['result']['addressMatches'][0]['coordinates'] longitude = coords['x'] latitude = coords['y'] print(f"纬度: {latitude}, 经度: {longitude}") else: print("没找到对应地址的地理坐标")清理冗余代码
删除重复的json.loads(response.text),response.json()已经把返回内容转成了Python字典,直接用data即可。基础环境检查
确保已经安装requests库,没装的话运行:pip install requests
内容的提问来源于stack exchange,提问作者Emily Herbert
相关产品推荐
相关产品推荐

