API的應用通常會處理json數據,剛好今天看到了jsonpython/331251.html">字符串和python字符串的區別,放一段代碼,區別一下子就看出來,的確json 庫為處理Json 數據提供了不少的便利。
import jsonjsonString = '{"arrayOfNums":[{"number":0},{"number":1},{"number":2}],"arrayOfFruits":[{"fruit":"apple"},{"fruit":"banana"},{"fruit":"pear"}]}'jsonObj = json.loads(jsonString)print(jsonObj.get("arrayOfNums"))print(jsonObj.get("arrayOfNums")[0].get('number'))#json 是一個字符串形式的。 沒有get方法#python 字符串有get方法 便于處理 json里面的數據下面是一段通過ip地址查詢地理位置信息的代碼,也貼上去,接口是免費的
import jsonfrom urllib.request import urlopendef getCountry(ipAddress): response = urlopen("http://freegeoip.net/json/"+ipAddress).read().decode('utf-8') responseJson = json.loads(response) print(responseJson) return responseJson.get("country_code")print(getCountry("50.78.253.58"))(代碼來自python網絡數據采集)
剛好看到,在貼個庫的用法上去,urllib.request.urltrieve 可以根據鏈接把文件下載下來,上代碼好理解一些
from urllib.request import urlretrievefrom urllib.request import urlopenfrom bs4 import BeautifulSouphtml = urlopen('http://www.pythonscraping.com')bs4 = BeautifulSoup(html,'xml')imageLocation = bs4.find("a",{"id":"logo"}).find("img")['src']urlretrieve(imageLocation,"logo.jpg") #urlretrieve 根據下載鏈接 可以把文件下載下來#把logo下載在當前目錄,名字叫logo.jpg以上這篇對json字符串與python字符串的不同之處詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答