学习如何使用Python中的HTTPResponse()类处理HTTP响应
发布时间:2023-12-24 20:46:28
在Python中,可以使用HTTPResponse()类来处理HTTP响应。HTTPResponse是一个类似文件对象的类,它由urllib库提供。
首先,我们需要导入urllib库:
import urllib.request
然后,我们可以使用urllib库中的urlopen()函数发送HTTP请求并获取HTTP响应。我们可以将返回的响应对象存储在一个变量中:
response = urllib.request.urlopen('http://www.example.com')
接下来,我们可以使用HTTPResponse对象的一些方法和属性来处理HTTP响应。
1. read()方法:读取HTTP响应的内容。可以将它存储在一个变量中:
html = response.read()
2. getheader()方法:获取指定HTTP头的值。可以传递一个头名称作为参数:
content_type = response.getheader('Content-Type')
3. getheaders()方法:获取所有的HTTP头。返回一个包含所有头名称和值的列表:
headers = response.getheaders()
4. code属性:获取HTTP响应的状态码:
status_code = response.code
下面是一个完整的例子,它使用HTTPResponse类来处理HTTP响应:
import urllib.request
response = urllib.request.urlopen('https://www.baidu.com')
# 读取HTTP响应的内容
html = response.read()
# 获取Content-Type头的值
content_type = response.getheader('Content-Type')
# 获取所有的HTTP头
headers = response.getheaders()
# 获取HTTP响应的状态码
status_code = response.code
print('Content-Type:', content_type)
print('Headers:', headers)
print('Status Code:', status_code)
print('HTML:', html)
这个例子发送HTTP请求到百度网站并获取响应。然后,它读取响应的内容、获取Content-Type头的值、获取所有的HTTP头和获取HTTP响应的状态码,并将它们打印出来。
使用HTTPResponse类可以方便地处理HTTP响应,从而可以进一步处理返回的数据或是做一些其他的操作。
