使用 HTTP 请求从网页导入文件

Python 数据导入进阶

Hugo Bowne-Anderson

Data Scientist at DataCamp

URL

  • 统一资源定位符(URL)
  • 指向网络资源
  • 关注:网页地址
  • 组成:
    • 协议标识符 - http:
    • 资源名称 - datacamp.com
  • 唯一指定网页地址
Python 数据导入进阶

HTTP

  • 超文本传输协议
  • Web 数据通信的基础
  • HTTPS:更安全的 HTTP
  • 访问网站 = 发送 HTTP 请求
    • GET 请求
  • urlretrieve() 执行 GET 请求
  • HTML:超文本标记语言
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...