HTTP错误404:找不到Post请求不工作

2024-05-23 20:13:23 发布

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

我想用邮政编码.io通过使用网站上显示的“批量查找邮政编码”从一堆邮政编码中获取经度和纬度。在

我试图将一个json对象传递给api点,正如文档中所示的那样,但是仍然得到标题中显示的错误。在

这是我的密码

allpostcodes = [i['postcode'] for i in _sortedstores()] # Getting postcodes from json file

data = {}
data['postcodes'] = allpostcodes # creating a dictionary and keeping `postcodes` and key and the postcode's as the value as shown in the example

_postcodearray = 'https://api.postcodes.io/%s' % json.dumps(data) # creating a json object and passing in the data
#_postcodearray = 'https://api.postcodes.io/%s' % data['postcodes'] #Not working



try:
    with urllib.request.urlopen(_postcodearray) as _postcodearray:
        a = _postcodearray.read()
        a = json.loads(a.decode('utf-8'))
        print(a)
except Exception as e:
    print(e)

我的数据变量在使用前的外观json.dump文件在上面{'postcodes': ['GU34 2QS', 'TN23 7DH', 'HP20 1DH']}

我也尝试过定期传递一个数组,结果却导致了同样的错误。如果您能为我的错误之处提供帮助/建议,我们将不胜感激。在


Tags: andtheiniocreatingapijsondata
1条回答
网友
1楼 · 发布于 2024-05-23 20:13:23
#!/usr/bin/env python3

import json
import urllib.request

allpostcodes = ["OX49 5NU", "M32 0JG", "NE30 1DP"]
#allpostcodes = [i['postcode'] for i in sortedstores] # Getting postcodes from json file

values = {}
# creating a dictionary and keeping `postcodes` and key and
# the postcode's as the value as shown in the example
values['postcodes'] = allpostcodes 

api_endpoint = 'https://api.postcodes.io/postcodes/'
data = json.dumps(values).encode('utf8')
req = urllib.request.Request(api_endpoint, data,
        headers={'content-type': 'application/json'})
try:
    with urllib.request.urlopen(req) as response:
        result = json.loads(response.read())
        print(json.dumps(result, indent=2))
except Exception as e:
    print(e)

相关问题 更多 >