開始使用免費開始

使用 urllib 在 Python 執行 HTTP 請求

現在你已了解 HTTP GET 請求的基礎,是時候自己動手做了。在這個互動式練習中,你會對 DataCamp 的伺服器發送 GET 請求,從本課程的第一個程式練習中擷取資訊:"https://campus.datacamp.com/courses/1606/4135?ex=2"

在下一個練習中,你會擷取實際的 HTML。不過現在,你要先封裝並送出請求,然後接收回應。

本練習屬於課程

Python 資料匯入進階

檢視課程

練習說明

  • 從子套件 urllib.request 匯入函式 urlopenRequest
  • 使用 Request() 對網址 "https://campus.datacamp.com/courses/1606/4135?ex=2" 建立請求,並指定給 request
  • 使用函式 urlopen() 送出請求,並將回應存入變數 response
  • 執行其餘程式碼來查看 response 的資料型別並關閉連線!

動手互動練習

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

# Import packages


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

# This packages the request: request


# Sends the request and catches the response: response


# Print the datatype of response
print(type(response))

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