一旭等、json
1.什么是json數(shù)據(jù)
json是一種具有特定語法的數(shù)據(jù)格式
2.json數(shù)據(jù)的語法
a.一個json數(shù)據(jù)只能有一個數(shù)據(jù)(有且只有一個)
b.這個數(shù)據(jù)的數(shù)據(jù)類型必須是json支持的數(shù)據(jù)類型
3.json支持的數(shù)據(jù)類型
a.數(shù)字類型(number):包含所有的數(shù)字需频,包括整數(shù)山橄、小數(shù)番官;例如:100,12.3
注意:整數(shù)前面不能加'+',支持科學(xué)計數(shù)法
b.字符串:使用雙引號括起來的數(shù)據(jù);例如:"saa"
c.布爾值:只有true和false
b.數(shù)組:相當(dāng)于Python的列表肴捉,用[]括起來鬓长,多個元素用逗號隔開;例如:[12,'asa']
e.字典:相當(dāng)于Python的字典巍糯,用{}括起來啸驯,多個鍵值對用逗號隔開,例如{"a":1}
f.空值:null相當(dāng)于Python中的None
4.Python處理json數(shù)據(jù)
1.將json數(shù)據(jù)轉(zhuǎn)換為Python數(shù)據(jù)(通過爬蟲獲取別人提供的json數(shù)據(jù)祟峦,在Python中處理)
Python中提供了json模塊罚斗,專門用來處理json數(shù)據(jù)
a.
json ---> Python
數(shù)字 --->int/float
字符串 ---> 字符串,可能雙引號會變成單引號
布爾 ---> bool宅楞,會將json中的true和false轉(zhuǎn)化為Python的大寫
數(shù)組 --->list
字典 ---->dict
空值(null) ---->None
b.loads
loads(字符串针姿,encodding=‘utf-8’) -將字符串中的json數(shù)據(jù)轉(zhuǎn)換成對應(yīng)的Python數(shù)據(jù)
8み骸!>嘁绞绒!注意:這兒的字符串中內(nèi)容必須是json數(shù)據(jù)
import json
def main():
content = json.loads('"aaaa"', encoding='utf-8')
print(content)
2.將Python中的數(shù)據(jù)轉(zhuǎn)換為json數(shù)據(jù)()
a.轉(zhuǎn)換方式
Python ---> json
int/float ---> 數(shù)字
str ---> 字符串
bool ---> True:true
list/tuple ---> 數(shù)組
dict ---> 字典
集合不能轉(zhuǎn)換為json數(shù)據(jù)
b.dumps(對象 ) -將指定的對象轉(zhuǎn)換成json數(shù)據(jù),以字符串的形式返回
這兒的對象指的就是Python數(shù)據(jù)
注意:返回值是字符串榕暇,并且字符串的內(nèi)容就是json數(shù)據(jù)
5.json文件處理
嚴(yán)格來說蓬衡,json文件是文件內(nèi)容是json的文件
load(文件對象) -將指定文件中的內(nèi)容讀出來,并且轉(zhuǎn)換成Python對應(yīng)的數(shù)據(jù)拐揭。
注意:這兒的文件對象對應(yīng)的文件必須是json文件
dump (對象撤蟆,文件對象) -將指定對象轉(zhuǎn)換成內(nèi)容是json格式的字符串,然后寫入指定的文件中
注意:這兒的對象對應(yīng)的類型必須是能夠轉(zhuǎn)換成json的數(shù)據(jù)類型
'''
studen = [
{'a': 's', 'as': 'as'},
{'a': 's', 'as': 'as'},
{'a': 's', 'as': 'awe'},
]
with open('tset1.json', 'w', encoding='utf-8') as test:
json.dump(studen, test)
練習(xí):用一個列表保存多個學(xué)生的信息堂污,寫函數(shù)向這個列表添加學(xué)生(姓名家肯、電話、成績)盟猖,要求數(shù)據(jù)本地化
all_students = []
print('================================')
addname = input('請輸入姓名:')
addage = int(input('請輸入年齡:'))
addscore = int(input('請輸入成績:'))
addtel = input('請輸入電話:')
def get_num():
num = 1
while True:
yield '1%03.d' % (num)
num += 1
num_gen = get_num()
def wg_input(addname, addage, addscore, addtel):
with open('all_students.json', encoding='utf-8') as stu:
all_students = json.load(stu)
all_students.append(
{'name': addname, 'num': next(num_gen), 'age': addage, 'score': addscore, 'tel': addtel})
with open('all_students.json', 'w', encoding='utf-8') as stu:
json.dump(all_students, stu)
wg_input(addname, addage, addscore, addtel)
二讨衣、requests
python中的數(shù)據(jù)請求(http請求),是第三方庫requests來提供的
1.requests第三方庫的使用
get/post方法都是發(fā)送請求獲取接口提供的數(shù)據(jù)
a.
get(url, params=None)
url - 字符串,需要獲取的數(shù)據(jù)的接口地址
params - 字典,參數(shù)列表(給服務(wù)器發(fā)送請求的時候需要傳給服務(wù)器的數(shù)據(jù))
https://www.apiopen.top/meituApi?page=1
完整的接口: 協(xié)議://主機(jī)地址/路徑?參數(shù)名1=值1&參數(shù)名2=值2
b.post(url, params=None, json=None)(暫時不管!)
response = requests.get('http://rap2api.taobao.org/app/mock/121184/studentsInfo')
print(response.json())
1.發(fā)送請求,并且獲取返回的數(shù)據(jù)
服務(wù)返回的數(shù)據(jù)叫響應(yīng)
response = requests.get('https://www.apiopen.top/meituApi?page=1')
# response = requests.get('https://www.apiopen.top/meituApi', {'page': 1})
print(response)
2.從響應(yīng)中獲取數(shù)據(jù)
a.獲取json數(shù)據(jù)
content_json = response.json() # 會自動將json數(shù)據(jù)轉(zhuǎn)換成python對應(yīng)的數(shù)據(jù)
print(type(content_json))
print(content_json)
# b.獲取字符串?dāng)?shù)據(jù)
content_text = response.text
print(type(content_text))
print(content_text)
# c.獲取二進(jìn)制數(shù)據(jù)(原始數(shù)據(jù))
content_bytes = response.content
print(content_bytes)
# 下載圖片
response2 = requests.get('http://tx.haiqq.com/uploads/allimg/170506/0H92Q915-1.jpg')
with open('luffy.jpg', 'wb') as f:
f.write(response2.content)
三式镐、異常捕獲
1.異常捕獲----讓本該報錯的代碼不報錯
知道某段代碼會出現(xiàn)異常反镇,但是又沒辦法避免,同時又不希望出現(xiàn)異常時程序崩潰娘汞;
這個時候就可以通過異常捕獲來讓程序不崩潰歹茶,來讓程序不崩潰并且自行處理異常
2.異常捕獲語法
a.try -except 可以捕獲所有異常
try:
代碼段1(可能出現(xiàn)異常的代碼)
except:
代碼段2(出現(xiàn)異常后的處理)
執(zhí)行過程:執(zhí)行代碼段1,如果代碼段1中出現(xiàn)異常你弦,程序不崩潰惊豺,直接執(zhí)行代碼段2
如果代碼段1沒有出現(xiàn)異常,不執(zhí)行代碼段2而是直接執(zhí)行后面的其他語句
b.try -except 錯誤類型(捕獲指定類型的異常 -只有代碼段1中出現(xiàn)了指定類型的異常才捕獲)
try:
代碼段1(可能出現(xiàn)異常的代碼)
except 錯誤類型:
代碼段2(出現(xiàn)異常后的處理)
c.try -except (錯誤類型1,錯誤類型2......)
try:
代碼段1(可能出現(xiàn)異常的代碼)
except (錯誤類型1禽作,錯誤類型2):
代碼段2(出現(xiàn)異常后的處理)
d.try - except 錯誤類型1 -except 錯誤類型2...(同時捕獲多種異常尸昧,并進(jìn)行不同處理)
try:
代碼段1(可能出現(xiàn)異常的代碼)
except 錯誤類型1:
代碼段2(出現(xiàn)異常后的處理)
except 錯誤類型1:
代碼段3(出現(xiàn)異常后的處理)
3.拋出異常 - 主動讓程序奔潰
raise 錯誤類型 -程序執(zhí)行到該行代碼,拋出指定類型的異常
說明:錯誤類型 -可以是系統(tǒng)提供的錯誤類型旷偿,也可以是自定義錯誤類型(要求這個值必須是一個類烹俗,而且exception的子類)
def main():
try:
number =int(input('請輸入一個數(shù)字:'))
print(number)
except:
print('輸入錯誤!')
練習(xí):輸入數(shù)字萍程,保存成int幢妄,如果輸入錯誤就繼續(xù)輸入,直到輸入正確為止
while True:
try:
number =int(input('請輸入一個數(shù)字:'))
print(number)
break
except:
print('輸入錯誤尘喝!')
class wgVaLueError(Exception):
def __tr__(self):
return '值錯誤磁浇!'