Requests库安装
pip install requests
注意:如果是在MAC的python3中安装,使用pip3 install requests
Requests库的方法
Request的基础方法

Requests的get()方法
get方法是我们做为爬虫最常用的使用方法
使用Requests模块,在一开始要导入Requests模块
import requests
然后获取某个网页
r = requests.get('http://www.baidu.com')
对响应内容进行处理,requests.get()方法会返回一个Response对象r,我们可以根据该对象的一些属性来获取请求的结果

Requests会基于HTTP头部对相应的编码做出有根据的猜测,当访问r.text的时候。Requests会使用其推测的文本编码,你可以找出Requests 使用了什么编码,并且能够使用 r.encoding
属性来改变它:
#r.encoding是推测的文本编码
print(r.encoding)
ISO-8859-1
#r.apparent_encoding是分析响应内容的文本编码
print(r.apparent_encoding)
utf-8
#可以通过改变r.encoding编码的格式来获取正确编码的内容r.text
r.encoding = r.apparent_encoding
如果想要查看请求是否获得成功,r.status_code属性可以获取到请求状态。200表示连接成功通过
Requests的head()方法

Requests的post()方法
post根据用户提交数据的不同,会在服务器端做出相应的处理
post方法是向数据库提交一个字符串

post方法是向数据库提交一个字典数据

Requests的request()方法
request方法为Requests库的基础方法,我们进入Requests库中查看,我们调用request.get()
方法其实是Requests库为来方便我们使用提供的一种封装方法。

request方法有三个参数
requests.request(method,url,**kwargs)
method:请求方式,对应get/put/post等7中

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

1.params:字典或字节序列,作为参数增加到URL中
kv = {'key':'value','key2':'value2'}
r = requests.request('GET','http://www.baidu.com',params=kv)
print(r.url)
http://www.baidu.com/?key=value&key2=value2
2.data:字典、字节序或文件对象,作为Request的内容,重点是作为向服务器提供或提交资源时使用
kv = {'key':'value','key2':'value2'}
r = requests.request('POST','http://www.baidu.com',data=kv)
body = '主体内容'
r = requests.request('POST','http://www.baidu.com',data=body)
3.json:JSON格式的数据,作为request的内容
kv = {'key':'value'}
r = requests.request('POST','http://www.baidu.com',json=kv)
4.headers:字典,HTTP定制头,可以模拟任意的浏览器信息向服务器发起访问
hd = {'user-agent':'Chrome/10'}
r = requests.request('POST','http://www.baidu.com',headers=hd)
5.cookies:字典或CookieJar,Request中的cookie
6.auth:元祖,支持HTTP认证功能
7.files:字典类型,传输文件,向某一个链接提供一个文件
fs = {'file':open('/Users/Desktop/Video/Python/5.Requests库的主要方法解析.mp4','rb')}
r = requests.request('POST','http://www.baidu.com',files=fs)
8.timeout:设定超时时间,秒为单位
r = requests.request('GET','http://www.baidu.com',timeout=10)
9.proxies:字典类型,设定访问代理服务器,可以增加登录认证
pxs = {'http':'http://user:pass@10.10.10.1:80',
'https':'https://10.10.10.1:8080'}
r = requests.request('GET','http://www.baidu.com',proxies=pxs)
10.allow_redirects: True/False,默认为Ture,重定向开关
11.stream: True/False,默认为Ture,获取内容是否立即下载
12.verify: True/False,默认为Ture,认证SSL证书开关
13.cert:本地SSL证书路径
网友评论