本答案頁包含 Python 爬蟲 HTTP 請求 的 4 道選擇題、4 道填空題和 4 道輸出預測題,每題都給出準確答案和簡短解釋。
答案已完整展示,建議先嘗試作答,再用本頁核對。第一次練習最好從互動練習頁開始。
User-Agent 請求頭用來標識什麼?
答案: 發起請求的客戶端
為什麼: 描述清楚的 User-Agent 告訴伺服器是哪個客戶端在存取。
為什麼要給請求設定超時?
答案: 避免卡住的連接一直掛起
為什麼: 超時限制客戶端等待多久後放棄。
哪個狀態碼表示請求成功?
答案: 200
為什麼: 2xx 狀態碼表示成功;200 是最常見的 OK 回應。
執行結果是什麼?
from urllib.request import Request
request = Request("https://example.com/docs", headers={"User-Agent": "PyPracticeBot/1.0"})
print(request.get_header("User-agent"))答案: PyPracticeBot/1.0
為什麼: get_header 回傳 User-Agent 請求頭中儲存的值。
補全 Request 的匯入。
from urllib.request import ____答案: Request
為什麼: Request 用來構造請求物件,不會立即發送。
補全儲存請求頭的關鍵字參數。
from urllib.request import Request
request = Request("https://example.com", ____={"User-Agent": "Bot/1.0"})
print(request.get_header("User-agent"))答案: headers
為什麼: headers 映射會傳給 Request 構造函式。
補全 2xx 成功狀態碼的上界。
status = 204
print(200 <= status < ____)答案: 300
為什麼: 成功回應是 200 到 299,所以不包含的上界是 300。
補全標識客戶端的請求頭名稱。
from urllib.request import Request
request = Request("https://example.com", headers={"____": "LearningBot/1.0"})
print(request.get_header("User-agent"))答案: User-Agent
為什麼: User-Agent 是標識客戶端的標準請求頭。
這段程式列印出什麼?
from urllib.request import Request
request = Request("https://example.com/a?x=1")
print(request.full_url)答案: https://example.com/a?x=1
為什麼: full_url 回傳請求中儲存的完整 URL。
程式碼的輸出結果是什麼?
from urllib.request import Request
request = Request("https://example.com", headers={"User-Agent": "MyBot/1.0"})
print(request.get_header("User-agent"))答案: MyBot/1.0
為什麼: 請求頭查詢回傳 headers 映射中提供的值。
螢幕上會顯示什麼?
status = 404
print("ok" if 200 <= status < 300 else "error")答案: error
為什麼: 404 不在 2xx 成功範圍內,所以條件表達式輸出 error。
這段程式碼會輸出什麼?
status = 429
print("retry" if status == 429 else "go")答案: retry
為什麼: 429 表示請求過多,所以輸出 retry。
先試一遍題目
打開 Python 爬蟲 HTTP 請求 練習頁,用即時回饋回答同樣的 12 道題。