在 Python 中使用 requests 執行 HTTP 請求
你已經用 urllib 套件練習發送 HTTP 請求,接下來要用更高階的 requests 函式庫完成同樣的事情。你會再次向 DataCamp 的伺服器請求 "http://www.datacamp.com/teach/documentation" 這個頁面。
注意:與先前使用 urllib 的練習不同,使用 requests 時不需要手動關閉連線!
本練習屬於課程
Python 資料匯入進階
練習說明
- 匯入套件
requests。 - 將目標 URL 指派給變數
url。 - 以單一函式
requests.get()打包並送出對該 URL 的請求,並將回應指派給變數r。 - 使用物件
r的text屬性,取得該網頁的 HTML 字串;將結果存入變數text。 - 按下 送出答案 以列印該網頁的 HTML。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import package
# Specify the url: url
# Packages the request, send the request and catch the response: r
# Extract the response: text
# Print the html
print(text)