Python,創建網路請求
Python提供了urllib標準庫包來創建網路請求。 使用以下代碼創建請求: from urllib import request url = 'https://dog.ceo/api/breeds/list/all' response = request.urlopen(url) content = response.read() print(content) 你也可以使用with語句來簡化: from urllib import request url = 'https://dog.ceo/api/breeds/list/all' with request.urlopen(url) as response: content = response.read() print(content) 響應是一個字節序列,你會注意到響應被包裹在b''字符串中: b'{"message":{"affenpinscher":[],"african":[],"airedale":[],"akita":[],"appenzeller":[],"australian":["shepherd"],"basenji":[],"beagle":[],"bluetick":[],"borzoi":[],"bouvier":[],"boxer":[],"brabancon":[],"briard":[],"buhund":["norwegian"],"bulldog":["boston","english","french"]},"status":"success"}' 使用content.decode('utf-8')將其解碼為UTF-8編碼的字符串。 這裡是從我的網站flavicopes.com獲取HTML內容的例子: from urllib import request url = 'https://flaviocopes.com' with request.urlopen(url) as response: content = response.read().decode('utf-8') print(content) 你可以使用json標準庫模塊將響應解析為JSON: from urllib import request import json url = 'https://dog.ceo/api/breeds/list/all' with request.urlopen(url) as response: content = response.read() data = json....