Request库的安装与使用 Request库的安装与使用

安装

pip install reqeusts

Requests库的7个主要使用方法

  • requests.request() 构造一个请求,支撑以下各方法的基础方法
  • requests.get() 获取HTML网页的主要方法,对应HTTP的GET方法
  • requests.head() 获取HTML网页头信息的方法,对应HTTP的HEAD
  • requests.post() 向HTML网页提交POST请求的方法,对应HTTP的POST
  • requests.put() 向HTML网页提交PUT请求的方法,对应HTTP的PUT
  • requests.patch() 向HTML网页提交局部修改请求,对应于HTTP的PATCH
  • requests.delete() 向HTML页面提交删除请求,对应HTTP的DELETE

Response对象的属性

  • r.status_code HTTP请求的返回状态,200表示连接成功,404表示失败
  • r.text HTTP响应的正文字符串
  • r.encoding 从HTTP header中猜测的响应内容编码方式
  • r.apparent_encoding 从内容中分析出的响应编码方式
  • r.content HTTP响应内容的二进制形式

使用get方法的流程

检查r.status_code,如果返回200,继续处理,如果返回404,则说明访问出错。

encoding 和 apparent_encoding的区别

encoding是header的charset中记录的编码,若没有改标签,则默认为iso-8859-1
apparent_encoding是分析文本内容中出现的字符确定的编码。
一般来说如果文本编码识别错误,可以将apprent_encoding赋值给r.encoding

Requests库的异常

requests.ConnectionError 网络连接错误异常,如DNS查询失败、拒绝连接
requests.HTTPError HTTP错误异常
requests.URLRquired URL确实异常
requests.TooManyRedirects 超过最大重定向次数,产生重定向异常
requests.ConnectTimeout: 远程连接超时异常
requests.Timeout: 请求URL超时,产生超时异常
r.raise_for_status() 如果返回的状态码不是200,则会产生requests HTTPError异常

request方法

requests.requst(method,url,**kwargs)

  • method:请求方式,对应get/put/post等7种

    r = requests.request(‘GET’,url,**kwargs)
    r = requests.request(‘HEAD’,url,**kwargs)
    r = requests.request(‘POST’,url,**kwargs)
    r = requests.request(‘PUT’,url,**kwargs)
    r = requests.request(‘PATCH’,url,**kwargs)
    r = requests.request(‘DELETE’,url,**kwargs)
    r = requests.request(‘OPTIONS’,url,**kwargs)

url:页面的链接

**kwargs: 控制访问的参数,共13个

  • params: 字典或字节序列,作为参数增加到url中
  • data: 字典、字节序列或文件对象,作为Request的内容
  • json: JSON格式的数据,作为Request的内容
  • header: 字典,HTTP定制头
hd = {'user-agent':'Chrome/10'}
r = requests.request('POST','HTTP://python123.io/ws',headers=hd)
  • cookies:字典或CookieJar,Request中的cookie
  • auth :元组,支持HTTP认证功能
  • files: 字典类型,传输文件
fs = {'file':open('data.xls','rb')}
r = requests.request('POST','http://python123.io/ws',files=fs)
  • timeout:给请求设置超时时间
  • proxies: 字典类型,设定访问代理服务器,可以增加登录认证
pxs = {'http':'http://user:pass@10.10.10.1':1234'
'http':'http://10.10.10.1:4321'
}
r = requests.request('GET','http://www.baidu.com',proxies=pxs)
  • allow_redirects: True/False,默认为True,重定向开关
  • stream: True/False,默认为True,获取内容立即下载开关
  • verify: True/False,默认为True,认证SSL证书开关
  • cert: 本地SSL证书路径