在 Python 中使用 urllib 执行 HTTP 请求
既然您已经了解了 HTTP GET 请求的基础知识,现在就来亲自实践一下。在本交互式练习中,您将向 DataCamp 自身的服务器发送 GET 请求,从本课程的第一个编程练习中提取信息:"https://campus.datacamp.com/courses/1606/4135?ex=2"。
在下一个练习中,您将提取页面的 HTML。本练习中,您需要先打包并发送请求,然后接收响应。
本练习是课程的一部分
Python 数据导入进阶
练习说明
- 从子包
urllib.request导入函数urlopen和Request。 - 使用函数
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()