我想使用 python 2.7 版本从 url 获取 json 数据.我试图导入 urllib 请求模块,但它对我不起作


import urllib.request
import json
from pprint import pprint
def main():
    url="https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
    data=urllib.request.urlopen(url).read()
    jsonData=json.loads(data.decode("utf-8"))
    pprint(jsonData)
if __name__ == '__main__':
    main()

有人可以帮助我吗?谢谢

也许您可以使用请求库而不是urllib,如下所示:

import requests
response=requests.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys")
jsonData=response.json()

您需要添加适当的导入。特别是,import urllib.request无法解析 Python2。我建议使用适当的IDE来向您说明这些错误。(当您尝试运行它时,您也会遇到这些错误(。下面是你重写的脚本,将urllib.request替换为urllib,它适用于Python2!

工作 Python2 (repl 在这里(:

import urllib
import json
from pprint import pprint
def main():
    url="https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
    data = urllib.urlopen(url).read()
    jsonData = json.loads(data.decode("utf-8"))
    pprint(jsonData)
if __name__ == "__main__":
    main()

更新

工作 Python3 (repl 在这里(:

import urllib.request
import json
from pprint import pprint
def main():
    url="https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
    data = urllib.request.urlopen(url).read()
    jsonData = json.loads(data.decode("utf-8"))
    pprint(jsonData)
main()

最新更新