【问题标题】:HTTP Error 404: Not Found - Post request not workingHTTP 错误 404:未找到 - 发布请求不起作用
【发布时间】:2019-10-14 07:03:01
【问题描述】:

我正在尝试使用 postcode.io 通过使用他们在网站https://postcodes.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']}

我还尝试定期传递导致相同错误的数组。任何关于我可能做错的帮助/建议将不胜感激。

【问题讨论】:

  • 您能否展示一下您的data 变量在请求之前的样子?
  • @Vishal 当然,我会在底部更新我的问题。
  • 能不能把网址改成_postcodearray = 'https://api.postcodes.io/postcodes/%s' % json.dumps(data)试试
  • @Vishal 我之前确实尝试过,但忘了提及,我仍然遇到同样的错误。
  • postcodes 肯定会在最后出现。否则它不是一个有效的网址。我尝试在我的桌面上使用 Postman 应用程序,它运行良好。

标签: python json python-3.x api python-requests


【解决方案1】:
#!/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)

【讨论】:

    猜你喜欢
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 2019-02-26
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多