requests库

来源:互联网 发布:淘宝女装拍摄 云南 编辑:程序博客网 时间:2024/06/07 19:06

一、安装

pip install requests

二、初试

import requests#使用get方法访问百度r = requests.get('http://www.baidu.com')#状态码r.status_code    Out[4]: 200#设置返回内容的编码格式为utf-8r.encoding='utf-8'  #显示返回对象的内容r.text

三、requests库的常用7个方法

方法 说明 备注 requests.request() 构造一个请求,支撑以下各方法 的基础方法 requests.get() 获取html页面的主要方法,对应于HTTP的GET GET:请求获取URL位置的资源 requests.head() 获取HTML网页头信息的方法,对应于HTTP的HEAD HEAD:请求获取URL位置资源的响应消息报告,即获得该资源的头部信息 requests.post() 向网页提交POST请求的方法,对应HTTP的POST POST:请求向URL位置的资源后附加新的数据 requests.put() 向网页提交PUT请求的方法,对应HTTP的PUT PUT:请求向URL位置存储一个资源,覆盖源URL位置的资源 requests.patch() 向网页提交局部修改请求,对应HTTP的PATCH 请求局部更新URL位置的资源,即改变该处资源的部分内容 requests.delete() 向网页提交删除请求,对应HTTP的DELETE 请求删除URL位置存储的资源

注意:put和patch方法的区别
假设URL位置上有一组数据userinfo,包括userid、username等20个字段
需求:用户修改了username,其他不变
采用patch,仅向URL提交username的局部更新请求。
采用put,必须将所有20个字段一并提交到URL,未提交字段被删除
patch的最主要用处:节省网络带宽

3.1 requests.get方法

requests.get(url, params=None, **kwargs)- url:拟获取页面的URL链接;格式 ---url='http://www.baidu.com'- params:url中的额外参数,字典或字节流格式,可选- **kwargs:12个访问控制的参数

url格式 http://host[:port][path]
host:合法的Internet主句域名或IP地址
port:端口后,缺省端口为80
path:请求资源的路径

3.1.1 Response对象的属性

Response对象的属性 说明 备注 r.status_code HTTP请求的返回状态,200表示连接成功,404表示失败 r.text HTTP响应内容的字符串形式,即url对应的页面内容 r.encoding 从HTTP header 中猜测的向相应内容的编码格式 r.apparent_encoding 从内容中分析的响应内容编码格式 r.content HTTP响应内容的二进制形式

3.1.2 异常

Requests库的异常 说明 备注 r.raise_for_status 如果不是200,产生异常requests.HTTPError requests.ConnectionError 网络连接错误,如DNS查询失败、防火墙拒绝连接 requests.HTTPError HTTP错误异常 requests.URLRequired URL缺失异常 requests.TooManyRedirects 超过最大重定向次数,产生重定向异常 requests.ConnetcTimeout 连接远程服务器超时异常 仅指连接到服务器的时间 requests.Timeout 请求URL超时,产生超时异常 客户端产生连接到收到返回内容的时间

3.1.3常用框架流程

Created with Raphaël 2.1.0requests.get()r.status_code是否是200正常结束r.text、r.encoding 、r.apparent_encoding、 r.content异常(404或其他)yesno

3.1.4常用框架

# -*- coding: utf-8 -*-"""Created on Thu May 18 20:33:42 2017@author: suning 1107914055@qq.com"""import requestsdef getHTMLText(url):    try:                r = requests.get(url)        r.raise_for_status()        r.encoding = r.apparent_encoding        #return r.text        return r.headers            except:        return '产生异常'      if __name__ == "__main__":    url = "http://www.baidu.com"    print(getHTMLText(url))

3.2 requests.head方法

r = requests.head("http://httpbin.org/get")print(r.headers){'Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Fri, 19 May 2017 05:38:50 GMT', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000622987747192', 'Content-Length': '267', 'Via': '1.1 vegur'}

3.3requests.post方法

post 一个字典

payload = {'key1':'value1','key2':'value2'}r = requests.post('http://httpbin.org/post',data = payload)print(r.text){  "args": {},   "data": "",   "files": {},   "form": {    "key1": "value1",     "key2": "value2"  },   "headers": {    "Accept": "*/*",     "Accept-Encoding": "gzip, deflate",     "Connection": "close",     "Content-Length": "23",     "Content-Type": "application/x-www-form-urlencoded",     "Host": "httpbin.org",     "User-Agent": "python-requests/2.12.4"  },   "json": null,   "origin": "223.167.127.235",   "url": "http://httpbin.org/post"}

post 一个字符串

n [22]: r = requests.post('http://httpbin.org/post',data = 'abxcc')print(r.text){  "args": {},   "data": "abxcc",   "files": {},   "form": {},   "headers": {    "Accept": "*/*",     "Accept-Encoding": "gzip, deflate",     "Connection": "close",     "Content-Length": "5",     "Host": "httpbin.org",     "User-Agent": "python-requests/2.12.4"  },   "json": null,   "origin": "223.167.127.235",   "url": "http://httpbin.org/post"}

put一个字典(覆盖原有数据)

r = requests.put('http://httpbin.org/put',data = payload)print(r.text){  "args": {},   "data": "",   "files": {},   "form": {    "key1": "value1",     "key2": "value2"  },   "headers": {    "Accept": "*/*",     "Accept-Encoding": "gzip, deflate",     "Connection": "close",     "Content-Length": "23",     "Content-Type": "application/x-www-form-urlencoded",     "Host": "httpbin.org",     "User-Agent": "python-requests/2.12.4"  },   "json": null,   "origin": "223.167.127.235",   "url": "http://httpbin.org/put"}

主要方法

requests.request(method,url,**kwargs)method:请求方式,对应get/put/post等7种url:拟获取页面的URL链接**kwargs:控制访问的参数,共13
Tables Are Cool

访问控制参数1:
params:字典或字节序列,作为参数增加到url中

>>> kv = {'key1':'value1','key2':'value2'}>>> r = requests.request('GET','http://python123.io/ws',params=kv)>>> print r.url'http://python123.io/ws?key1=value1&key2=value2'

访问控制参数2:
data:字典、字节序列或文件对象,作为Request的内容

#data是字典>>>  payload = {'key1':'value1','key2':'value2'}>>>  r = requests.post('http://httpbin.org/post',data = payload)>>>  print(r.url)http://httpbin.org/post>>>  print(r.text){  "args": {},   "data": "",   "files": {},   "form": {    "key1": "value1",     "key2": "value2"  },   "headers": {    "Accept": "*/*",     "Accept-Encoding": "gzip, deflate",     "Connection": "close",     "Content-Length": "23",     "Content-Type": "application/x-www-form-urlencoded",     "Host": "httpbin.org",     "User-Agent": "python-requests/2.12.4"  },   "json": null,   "origin": "223.167.127.235",   "url": "http://httpbin.org/post"}
#data是字符串>>>   r = requests.post('http://httpbin.org/post',data = 'text')>>>   print(r.url)'http://httpbin.org/post'>>>   print(r.text){  "args": {},   "data": "text",   "files": {},   "form": {},   "headers": {    "Accept": "*/*",     "Accept-Encoding": "gzip, deflate",     "Connection": "close",     "Content-Length": "4",     "Host": "httpbin.org",     "User-Agent": "python-requests/2.12.4"  },   "json": null,   "origin": "223.167.127.235",   "url": "http://httpbin.org/post"}
#data是文件对象>>>   file = open('D:/file1.txt',mode='r')>>>   r = requests.post('http://httpbin.org/post',data = file)>>>   r.url'http://httpbin.org/post'>>>   print(r.text){  "args": {},   "data": "iiiiiiiiiiii:",   "files": {},   "form": {},   "headers": {    "Accept": "*/*",     "Accept-Encoding": "gzip, deflate",     "Connection": "close",     "Content-Length": "13",     "Host": "httpbin.org",     "User-Agent": "python-requests/2.12.4"  },   "json": null,   "origin": "223.167.127.235",   "url": "http://httpbin.org/post"}

访问控制参数3:
json:JSON格式的数据,作为Request的内容

>>>   kv = {'key1': 'value1', 'key2': 'value2'}>>>   r = requests.request('POST','http://python123.io/ws',json=kv)>>>   print(r.url)'http://python123.io/ws'>>>   print(r.text)Not Found

访问控制参数4:
headers:字典,HTTP定制头

hd = {'user-agent','Chrome/10'}r = requests.request('POST','http://python123.io/ws',headers=hd)

访问控制参数5:
cookies:字典或CookerJar,request中的cookie
访问控制参数6:
auth:元组,支持HTTP认证功能
访问控制参数7:
files:字典类型,传输文件

fs = {'file':open('D:/data.xls','rb')}r = requests.request('POST','http://python123.io/ws',files=fs)

访问控制参数8:
timeout:设定超时时间,单位为秒

r = requests.request('GET','http://www.baidu.com',timeout=10)

访问控制参数9:
proxiex:字典类型,设定访问代理服务器,可以增加登录认证

>>> pxs = {'http':'http://user:pass@10.10.10.1:1234' 'https':'https://10.10.10.1:4321'}>>> r =requests.request('GET','http://www.baiud.com',proxies=pxs)

访问控制参数10:
allow_redirects:True/False,默认为True,默认为True,重定向开关
访问控制参数11:
stream:True/False,默认为True,获取内容立即下载开关
访问控制参数12:
verify:True/False,默认为True,认证SSL证书开关
访问控制参数13:
cert:本地SSL证书路径

应用

百度的关键词接口:
https:www.baidu.com/s?wd=keyword

kv = {'wd':'keyword'}r = requests.get('http://www.baidu.com/s',params=kv)

360的关键词接口
http://www.so.com/s?q=keyword

kv = {'q':'keyword'}r = requests.get('http://www.so.com/s',params=kv)

图片爬取

#!/usr/local/python-2.7.13/bin/virtualenv python# -*- coding: utf-8 -*-"""Created on Thu May 18 20:33:42 2017@author: suning 1107914055@qq.com"""import requestsimport osurl = "http://www.qzone.la/DownFile/354878/1448965"root = "/tmp/pic/"path = root + url.split('/')[-1] + ".jpg"try:    if not os.path.exists(root):        os.mkdir(root)    if not os.path.exists(path):        r = requests.get(url)        with open(path,'wb') as f:            f.write(r.content)            f.close()            print('文件以保存')    else:        print('文件已存在')except:    print('爬取失败')