python urllib库 HTTPResponse对象用法 简介

不管是使用urllib.request.urlopen()方法,还是使用opener.open()方法,都返回同样类型的HTTPResponse对象,用法总结如下:

# !/usr/bin/env python
# -*- coding:utf-8 -*-
 
from urllib import request
from urllib import response
 
URL="http://www.baidu.com/"
 
# 构造请求头信息
# 反反爬虫:设置User-Agent
request_headers={
    "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36"
}
 
# 构造请求对象,并添加请求头
req=request.Request(URL,headers=request_headers)
# 发起请求
resp=request.urlopen(req)
 
 
print(type(resp))   # <class 'http.client.HTTPResponse'>
# 获取HTTP协议版本号(10 for HTTP/1.0, 11 for HTTP/1.1)
print(resp.version)
 
# 获取响应码
print(resp.status)
print(resp.getcode())
 
# 获取响应描述字符串
print(resp.reason)
 
# 获取实际请求的页面url(防止重定向用)
print(resp.geturl())
 
# 获取特定响应头信息
print(resp.getheader(name="Content-Type"))
# 获取响应头信息,返回二元元组列表
print(resp.getheaders())
# 获取响应头信息,返回字符串
print(resp.info())
 
# 读取响应体
print(resp.readline().decode('utf-8'))
print(resp.read().decode('utf-8'))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值