使用 urllib 在 Python 中打印 HTTP 请求结果
您刚刚打包并发送了一个指向 "https://campus.datacamp.com/courses/1606/4135?ex=2" 的 GET 请求,并捕获了返回结果。您看到该返回结果是一个 http.client.HTTPResponse 对象。问题是:这个响应可以做什么?
因为它来自一个 HTML 页面,您可以对其进行"读取"以提取 HTML。实际上,http.client.HTTPResponse 对象有一个关联的 read() 方法。在本练习中,您将基于之前的工作,提取响应并打印其中的 HTML。
本练习是课程的一部分
Python 数据导入进阶
练习说明
- 使用
urlopen()发送请求,并像上一题一样将响应保存到变量response。 - 使用
read()方法提取响应内容,并将结果保存到变量html。 - 打印字符串
html。 - 点击提交以执行以上所有步骤并关闭响应:请保持整洁!
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import packages
from urllib.request import urlopen, Request
# Specify the url
url = "https://campus.datacamp.com/courses/1606/4135?ex=2"
# This packages the request
request = Request(url)
# Sends the request and catches the response: response
# Extract the response: html
# Print the html
# Be polite and close the response!
response.close()