揭秘Python中的JSON數據格式與Requests模塊
作者:華安9527
JSON數據格式和Requests模塊在現代編程中扮演著不可或缺的角色。JSON作為一種輕量級的數據交換格式,廣泛應用于Web服務之間的數據傳輸;而Requests庫則是Python中最流行的HTTP客戶端庫,用于發起HTTP請求并與服務器交互。
引言:
JSON數據格式和Requests模塊在現代編程中扮演著不可或缺的角色。JSON作為一種輕量級的數據交換格式,廣泛應用于Web服務之間的數據傳輸;而Requests庫則是Python中最流行的HTTP客戶端庫,用于發起HTTP請求并與服務器交互。今天,我們將通過10個精選的代碼示例,一同深入了解這兩個重要工具的使用。
1.創建并解析JSON數據
import json
# 創建JSON數據
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = json.dumps(data) # 將Python對象轉換為JSON字符串
print(json_data) # 輸出:{"name": "John", "age": 30, "city": "New York"}
# 解析JSON數據
json_string = '{"name": "Jane", "age": 28, "city": "San Francisco"}'
parsed_data = json.loads(json_string) # 將JSON字符串轉換為Python字典
print(parsed_data) # 輸出:{'name': 'Jane', 'age': 28, 'city': 'San Francisco'}
2.使用Requests發送GET請求
import requests
response = requests.get('https://api.github.com')
print(response.status_code) # 輸出HTTP狀態碼,如:200
print(response.json()) # 輸出響應體內容(假設響應是JSON格式)
# 保存完整的響應信息
with open('github_response.json', 'w') as f:
json.dump(response.json(), f)
3.發送帶參數的GET請求
params = {'q': 'Python requests', 'sort': 'stars'}
response = requests.get('https://api.github.com/search/repositories', params=params)
repos = response.json()['items']
for repo in repos[:5]: # 打印前5個搜索結果
print(repo['full_name'])
4.發送POST請求
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = requests.post('http://httpbin.org/post', jsnotallow=payload, headers=headers)
print(response.json())
5.設置超時時間
requests.get('http://example.com', timeout=5) # 設置超時時間為5秒
6.處理Cookies
# 保存cookies
response = requests.get('http://example.com')
cookies = response.cookies
# 發送帶有cookies的請求
requests.get('http://example.com', cookies=cookies)
7.自定義HTTP頭部信息
headers = {'User-Agent': 'My-Custom-UA'}
response = requests.get('http://httpbin.org/headers', headers=headers)
print(response.text)
8.下載文件
url = 'https://example.com/image.jpg'
response = requests.get(url)
# 寫入本地文件
with open('image.jpg', 'wb') as f:
f.write(response.content)
9.處理身份驗證
from requests.auth import HTTPBasicAuth
response = requests.get('https://example.com/api', auth=HTTPBasicAuth('username', 'password'))
10.重試機制
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
# 創建一個重試策略
retry_strategy = Retry(
total=3,
status_forcelist=[429, 500, 502, 503, 504],
backoff_factor=1,
)
# 添加重試策略到適配器
adapter = HTTPAdapter(max_retries=retry_strategy)
# 將適配器添加到會話
session = requests.Session()
session.mount('http://', adapter)
session.mount('https://', adapter)
response = session.get('https://example.com')
結語:
通過上述10個Python中JSON數據格式與Requests模塊的實戰示例,相信您對它們的使用有了更為深入的理解。熟練掌握這兩種工具將極大提升您在Web開發、API調用等方面的生產力。請持續關注我們的公眾號,獲取更多Python和其他編程主題的精彩內容!
責任編輯:華軒
來源:
測試開發學習交流