【python爬虫自学笔记】-----python3 requests库用法

requests比urllib2模块更简洁。支持HTTP连接保持和连接池,使用cookie保持会话,文件上传,自动响应内容的编码,国际化的URL和POST数据自动编码。在python内置模块的基础上进行了高度封装,从而使得python进行网络请求时,变得人性化,使用requests库可以轻而易举完成浏览器可有的任何操作。会自动实现持久连接keep-alive。

主要方法

方法 解释
requests.request() 构造一个请求,支持以下各种方法
requests.get() 获取html的主要方法
requests.head() 获取html头部信息的主要方法
requests.post() 向html网页提交post请求的方法
requests.put() 向html网页提交put请求的方法
requests.patch() 向html提交局部修改的请求
requests.delete() 向html提交删除请求

(1)requests.get(url,params,**kwargs)

**kwargs:12个控制访问参数;

params:字典或字节序列,作为参数增加到url中,使用这个参数可以把一些键值对以例如kv={'key1':'value1','key2':'value2'}模式增加到url中。示例:r = requests.request('GET','http://www.python.org',params=kw);

data:字典,字节序列或者文件对象,与params不同的是,data提交的数据不放在url链接中,而是放在url链接对应位置的地方作为数据来存储。它也可以接受一个字符串对象;

json:json格式的数据,作为内容部分可以向服务器提交。例如:kv={'key1':'value1'}, r=requests.request('POST','http://baidu.com',json=kv);

headers:字典类型;

cookies:字典或者cookiejar,指的是从http中解析cookie;

auth:元组,用来支持http认证功能;

files:字典,用来向服务器传输文件时使用的字段;fs={'files':'open('data.txt','rb')'};

timeout:设定超时时间,单位为秒。发起get请求时,如果早timeout时间内请求内容没有返回,将产生一个异常;

proxies:字典,用来设置访问代理服务器;

allow_redirects:开关,表示是否允许对url进行重定向,默认为True;

stream:开关,指是否对获取内容进行立即下载,默认为true;

verify:开关,用于认证SSL证书,默认值为True;

cent:用于设置保存本地SSL证书路径

request请求返回一个包含服务器资源的response对象,具有以下属性:

属性 说明
r.status_code http请求的返回状态,若为200则表示请求成功。
r.text http响应内容的字符串形式,即返回的页面内容
r.encoding 从http header 中猜测的相应内容编码方式
r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)
r.content http响应内容的二进制形式
#获取当前编码
print(r.encoding)
#设置编码
r.encoding = 'utf-8'
#以encoding解析返回内容,字符串方式的响应体,会自动根据响应头部的字符编码进行解码
print(r.text)
#以字节形式(二进制)返回,字节方式的响应体,会自动解码gzip和deflate压缩
print(r.content)
#以字典对象储存服务器响应头,但是这个字典不区分大小写,若键值不存在返回None
print(r.headers)
#返回响应状态码
print(r.status_code)
#返回原生响应体,也就是urllib的response对象,使用r.raw.read()方法
print(r.raw)
#查看是否登录成功
print(r.ok)

异常:捕捉异常使用r.raise_for_status()语句,该语句在方法内部判断r/status_code是否等于200,如果不等于,则抛出异常;

import requests
url = 'http://www.baidu.com'
try:
    r = requests.get(url,timeour = 30) #设置超时时间
    r.raise_for_status()  #如果状态不是200,引发异常
    r.encoding = r.apparent_encoding #配置编码
    print(r.text)
except:
     print('产生异常')

D:\develop\Anaconda3\python.exe D:/thislove/pythonworkspace/blogspark/requests_test.py
产生异常

Process finished with exit code 0

(2)requests.head()

r = requests.head('http://httpbin.org/get')
print(r.headers)
print(r.text)

D:\develop\Anaconda3\python.exe D:/thislove/pythonworkspace/blogspark/requests_test.py
{'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Date': 'Tue, 07 Aug 2018 13:17:49 GMT', 'Content-Type': 'application/json', 'Content-Length': '265', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'Via': '1.1 vegur'}


Process finished with exit code 0

(3)requests.post():可以传字典和一个字符串

#传字典
payload = {'key1':'value1','key2':'value2'}
r = requests.post('http://httpbin.org/post',data=payload)
print(r.text)

D:\develop\Anaconda3\python.exe D:/thislove/pythonworkspace/blogspark/requests_test.py
{
  "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.18.4"
  }, 
  "json": null, 
  "origin": "110.247.38.5", 
  "url": "http://httpbin.org/post"
}


Process finished with exit code 0
#传字符串
r = requests.post('http://httpbin.org/post',data='helloworld')
print(r.text)
D:\develop\Anaconda3\python.exe D:/thislove/pythonworkspace/blogspark/requests_test.py
{
  "args": {}, 
  "data": "helloworld", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "10", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "json": null, 
  "origin": "110.247.38.5", 
  "url": "http://httpbin.org/post"
}


Process finished with exit code 0

(4)requests.put()

payload = {'key1':'value1','key2':'value2'}
r = requests.put('http://httpbin.org/put',data=payload)
print(r.text)
D:\develop\Anaconda3\python.exe D:/thislove/pythonworkspace/blogspark/requests_test.py
{
  "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.18.4"
  }, 
  "json": null, 
  "origin": "110.247.38.5", 
  "url": "http://httpbin.org/put"
}


Process finished with exit code 0

(5)requests.patch():与put方法类似,用patch仅需要提交需要修改的字段,使用put时,必须将20个字段一起提交到url,未提交的字段将会被删除,patch方法可以节省网路带宽;

(6)requests.request(method,url,**kwargs):method:‘GET’,'POST','HEAD','PUT','PATCH';

猜你喜欢

转载自blog.csdn.net/m0_38103546/article/details/81463256