從網路以 HTTP 請求匯入檔案

Python 資料匯入進階

Hugo Bowne-Anderson

Data Scientist at DataCamp

URL

  • Uniform/Universal Resource Locator
  • 指向網路資源的參照
  • 重點:網址
  • 組成:
    • 通訊協定識別碼 - http:
    • 資源名稱 - datacamp.com
  • 能唯一指定網路位址
Python 資料匯入進階

HTTP

  • HyperText Transfer Protocol
  • 網路資料通訊的基礎
  • HTTPS:較安全的 HTTP 形式
  • 造訪網站=送出 HTTP 請求
    • GET 請求
  • urlretrieve() 會執行 GET 請求
  • HTML:HyperText Markup Language
Python 資料匯入進階

使用 urllib 發出 GET 請求

from urllib.request import urlopen, Request
url = "https://www.wikipedia.org/"
request = Request(url)
response = urlopen(request)
html = response.read()
response.close()
Python 資料匯入進階

使用 requests 發出 GET 請求

ch_1_2.026.png

  • 被「英國政府、Amazon、Google、Twilio、NPR、Obama for America、Twitter、Sony,以及不具名的美國聯邦機構」採用
Python 資料匯入進階

使用 requests 發出 GET 請求

  • 最常被下載的 Python 套件之一
import requests
url = "https://www.wikipedia.org/"
r = requests.get(url)
text = r.text
Python 資料匯入進階

一起來練習吧!

Python 資料匯入進階

Preparing Video For Download...