程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python request url json和多層嵌套

編輯:Python
1、調用url接口
#!/usr/bin/python
import requests
import json
def get_news():
"""獲取金山詞霸每日一句,英文和翻譯"""
url = "http://open.iciba.com/dsapi/"
# r = requests.get(url)
r = requests.get(url).text
d = json.loads(r)
print(type(r))
print(type(d))
print(d)
print(d.keys())
# 取出key對應的value
print(d['note'])
if __name__ == "__main__":
res = get_news()

結果

<class 'str'>
<class 'dict'>
{'sid': '4535', 'tts': 'https://staticedu-wps.cache.iciba.com/audio/04b09bf426c7b87095281d00a5f0941d.mp3', 'content': 'Those who follow the light will eventually be radiant.', 'note': '追光者終將光芒萬丈。', 'love': '0', 'translation': '新版每日一句', 'picture': 'https://staticedu-wps.cache.iciba.com/image/e8c6e99671f9797106bc2a60f6cture2': 'https://staticedu-wps.cache.iciba.com/image/0dfd35fcad9190747d8bd3cd2c91c758.jpg', 'caption': '詞霸每日一句', 'dateline': '2022-06-26', 's_pv': '0', 'sp_pv':'fenxiang_img': 'https://staticedu-wps.cache.iciba.com/image/d83cc3372ad490a481170a92050767bb.jpg', 'picture3': 'https://staticedu-wps.cache.iciba.com/image/05041b6b2fdc4b862d1f15bdd8b947c2.jpg', 'picture4': 'https://staticedu-wps.cache.iciba.com/image/b1e20fd1986c4caf666d78f8d0cb865a.jpg', 'tags': []}
dict_keys(['sid', 'tts', 'content', 'note', 'love', 'translation', 'picture', 'picture2', 'caption', 'dateline', 's_pv', 'sp_pv', 'fenxiang_img', 'picture3', 'picture4', 'tags'])
追光者終將光芒萬丈。
 

2、取出多層嵌套

import json

s = '{"data":{"yesterday":{"date":"11日星期二","high":"高溫 33℃","fx":"西南風","low":"低溫 26℃","fl":"微風","type":"陣雨"},"city":"杭州","aqi":"56","forecast":[{"date":"12日星期三","high":"高溫 36℃","fengli":"微風級","low":"低溫 28℃","fengxiang":"西南風","type":"多雲"},{"date":"13日星期四","high":"高溫 37℃","fengli":"微風級","low":"低溫 28℃","fengxiang":"西南風","type":"多雲"},{"date":"14日星期五","high":"高溫 36℃","fengli":"微風級","low":"低溫 28℃","fengxiang":"南風","type":"多雲"},{"date":"15日星期六","high":"高溫 36℃","fengli":"微風級","low":"低溫 27℃","fengxiang":"南風","type":"多雲"},{"date":"16日星期天","high":"高溫 36℃","fengli":"微風級","low":"低溫 27℃","fengxiang":"東南風","type":"晴"}],"ganmao":"各項氣象條件適宜,發生感冒機率較低。但請避免長期處於空調房間中,以防感冒。","wendu":"31"},"status":1000,"desc":"OK"}'

t = json.loads(s)

print(t['data']['yesterday']['high'])


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved