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.loads(content)
print(data['status'])
如果你需要指定查詢參數,使用urllib.parse
方法構建查詢字符串:
from urllib import request, parse
url = 'https://api.thecatapi.com/v1/images/search'
parms = {
'limit' : 5,
'page' : 1,
'order' : 'Desc'
}
querystring = parse.urlencode(parms)
with request.urlopen(url + '?' + querystring) as response:
content = response.read().decode('utf-8')
print(content)
這就是內置的urllib
包。
爲了方便起見,你可能想使用requests
包,它不是Python標準庫的一部分,但相當受歡迎。