開發與維運

requests模塊的使用

本文來自於千鋒教育在阿里雲開發者社區學習中心上線課程《Python入門2020最新大課》,主講人姜偉。

requests模塊的使用

除了使用瀏覽器給服務器發送請求以外,我們還可以使用第三方模塊requests用代碼來給服務器發送器請求,並獲取結果。

# requests 模塊是第三方的模塊,可以用來發送網絡連接
# pip install requests

import requests

response = requests.get('http://127.0.0.1:8090')
# print(response)  結果是一個Response對象

# content 指的是返回的結果,是一個二進制,可以用來傳遞圖片
# print(response.content.decode('utf8'))  # 將二進制解碼成為字符串

# 獲取到的結果就是一個文本
print(response.text)

print(response.status_code)  # 200

# 如果返回的結果是一個 json 字符串,可以解析json字符串
# print(response.json())

r = requests.get('http://127.0.0.1:8090/test')
t = r.text  # 獲取到 json 字符串
print(t, type(t))  # {"name": "zhangsan", "age": 18} <class 'str'>

j = r.json()  # 把 json 字符串解析成為python裡對應的數據類型
print(j, type(j))  # {'name': 'zhangsan', 'age': 18} <class 'dict'>

配套視頻

Leave a Reply

Your email address will not be published. Required fields are marked *