JSON數據格式和Requests模塊在現代編程中扮演著不可或缺的角色。JSON作為一種輕量級的數據交換格式,廣泛應用于Web服務之間的數據傳輸;而Requests庫則是Python中最流行的HTTP客戶端庫,用于發起HTTP請求并與服務器交互。今天,我們將通過10個精選的代碼示例,一同深入了解這兩個重要工具的使用。
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 requestsresponse = requests.get('https://api.github.com')print(response.status_code) # 輸出HTTP狀態碼,如:200print(response.json()) # 輸出響應體內容(假設響應是JSON格式)# 保存完整的響應信息with open('github_response.json', 'w') as f: json.dump(response.json(), f)
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'])
payload = {'key1': 'value1', 'key2': 'value2'}headers = {'Content-Type': 'application/json'}response = requests.post('http://httpbin.org/post', jsnotallow=payload, headers=headers)print(response.json())
requests.get('http://example.com', timeout=5) # 設置超時時間為5秒
# 保存cookiesresponse = requests.get('http://example.com')cookies = response.cookies# 發送帶有cookies的請求requests.get('http://example.com', cookies=cookies)
headers = {'User-Agent': 'My-Custom-UA'}response = requests.get('http://httpbin.org/headers', headers=headers)print(response.text)
url = 'https://example.com/image.jpg'response = requests.get(url)# 寫入本地文件with open('image.jpg', 'wb') as f: f.write(response.content)
from requests.auth import HTTPBasicAuthresponse = requests.get('https://example.com/api', auth=HTTPBasicAuth('username', 'password'))
from requests.adapters import HTTPAdapterfrom 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和其他編程主題的精彩內容!
本文鏈接:http://www.tebozhan.com/showinfo-26-83616-0.html揭秘Python中的JSON數據格式與Requests模塊
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: C# 中的 HTTP 請求