Python3 使用 urllib 与 json 模块解析天气数据接口

山海之间
山海之间
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍如何在 Python3 中利用 urllib.request 获取远程天气数据,并通过 json.loads 将字符串转换为字典对象。通过提取 weatherinfo 字段中的城市、温度、天气状况及编码信息,展示从网络请求到数据解析的完整流程,帮助开发者快速掌握基础的网络数据处理技巧。

Python3 处理JSON的实例详解

实现过程非常直观且易于上手。

import os, io, sys, re, time, base64, json
import webbrowser, urllib.request




def main():
  "main function"
  url = "http://m.weather.com.cn/data/101010100.html"
  stdout=urllib.request.urlopen(url)
  weatherInfo= stdout.read().decode('utf-8')
  #print(weatherInfo)
  jsonData = json.loads(weatherInfo)



生成并输出JSON格式的数据结果。

 szCity = jsonData["weatherinfo"]["city"]
  print("城市: ", szCity)
  szTemp = jsonData["weatherinfo"]["temp1"]
  print("温度: ", szTemp)
  szWeather1 = jsonData["weatherinfo"]["weather1"]
  print("天气情况: ",szWeather1)
  szCityid = jsonData["weatherinfo"]["cityid"]
  print("城市编码: ",szCityid)
  
if __name__ == '__main__':
  main()

若在阅读过程中遇到任何疑问,欢迎在下方留言或前往社区参与讨论。感谢各位的阅读,希望本文的内容能对大家有所帮助,同时也感谢大家对本站的支持!

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表