開始使用免費開始

使用 urllib 在 Python 中列印 HTTP 請求結果

你剛剛已經封裝並送出了對 "https://campus.datacamp.com/courses/1606/4135?ex=2" 的 GET 請求,並成功接住了回應。你也看到這個回應是一個 http.client.HTTPResponse 物件。剩下的問題是:你可以對這個回應做什麼?

由於它來自一個 HTML 網頁,你可以「讀取」它以擷取 HTML。事實上,http.client.HTTPResponse 物件提供了 read() 方法。在這個練習中,你會延續前一題的成果,擷取回應並列印出 HTML。

本練習屬於課程

Python 資料匯入進階

檢視課程

練習說明

  • 使用 urlopen() 送出請求,並如同上一題一樣,將回應存到變數 response
  • 使用 read() 方法擷取回應,並把結果存到變數 html
  • 列印字串 html
  • 按下送出以執行以上所有步驟,並關閉回應:保持整潔!

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import packages
from urllib.request import urlopen, Request

# Specify the url
url = "https://campus.datacamp.com/courses/1606/4135?ex=2"

# This packages the request
request = Request(url)

# Sends the request and catches the response: response


# Extract the response: html


# Print the html


# Be polite and close the response!
response.close()
編輯並執行程式碼