答案頁 · 12 道題

Python 爬蟲 HTTP 請求練習答案

本頁彙整 Python 爬蟲 HTTP 請求 的 12 道練習。先做練習頁,再回到這裡核對準確答案和原因。

快速答案

本答案頁包含 Python 爬蟲 HTTP 請求 的 4 道選擇題、4 道填空題和 4 道輸出預測題,每題都給出準確答案和簡短解釋。

答案已完整展示,建議先嘗試作答,再用本頁核對。第一次練習最好從互動練習頁開始。

01 · 選擇題

User-Agent 請求頭用來標識什麼?

  1. 頁面的 CSS 檔案
  2. 發起請求的客戶端正確答案
  3. 回應編碼
  4. 伺服器資料庫

答案: 發起請求的客戶端

為什麼: 描述清楚的 User-Agent 告訴伺服器是哪個客戶端在存取。

02 · 選擇題

為什麼要給請求設定超時?

  1. 避免卡住的連接一直掛起正確答案
  2. 讓 HTML 變合法
  3. 跳過 robots.txt
  4. 壓縮圖片

答案: 避免卡住的連接一直掛起

為什麼: 超時限制客戶端等待多久後放棄。

03 · 選擇題

哪個狀態碼表示請求成功?

  1. 404
  2. 500
  3. 200正確答案
  4. 301

答案: 200

為什麼: 2xx 狀態碼表示成功;200 是最常見的 OK 回應。

04 · 選擇題

執行結果是什麼?

from urllib.request import Request
request = Request("https://example.com/docs", headers={"User-Agent": "PyPracticeBot/1.0"})
print(request.get_header("User-agent"))
  1. docs
  2. None
  3. PyPracticeBot/1.0正確答案
  4. example.com

答案: PyPracticeBot/1.0

為什麼: get_header 回傳 User-Agent 請求頭中儲存的值。

05 · 填空題

補全 Request 的匯入。

from urllib.request import ____

答案: Request

為什麼: Request 用來構造請求物件,不會立即發送。

06 · 填空題

補全儲存請求頭的關鍵字參數。

from urllib.request import Request
request = Request("https://example.com", ____={"User-Agent": "Bot/1.0"})
print(request.get_header("User-agent"))

答案: headers

為什麼: headers 映射會傳給 Request 構造函式。

07 · 填空題

補全 2xx 成功狀態碼的上界。

status = 204
print(200 <= status < ____)

答案: 300

為什麼: 成功回應是 200 到 299,所以不包含的上界是 300。

08 · 填空題

補全標識客戶端的請求頭名稱。

from urllib.request import Request
request = Request("https://example.com", headers={"____": "LearningBot/1.0"})
print(request.get_header("User-agent"))

答案: User-Agent

為什麼: User-Agent 是標識客戶端的標準請求頭。

09 · 輸出預測

這段程式列印出什麼?

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。

10 · 輸出預測

程式碼的輸出結果是什麼?

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 映射中提供的值。

11 · 輸出預測

螢幕上會顯示什麼?

status = 404
print("ok" if 200 <= status < 300 else "error")

答案: error

為什麼: 404 不在 2xx 成功範圍內,所以條件表達式輸出 error。

12 · 輸出預測

這段程式碼會輸出什麼?

status = 429
print("retry" if status == 429 else "go")

答案: retry

為什麼: 429 表示請求過多,所以輸出 retry。

先試一遍題目

打開 Python 爬蟲 HTTP 請求 練習頁,用即時回饋回答同樣的 12 道題。

練習本課