Requests 让HTTP服务人类
Requests 库是比 ‘亲儿子’ 的urllib 库还好用。Requests 简化了 urllib 的诸多冗杂且无意义的操作, 并提供了强大的功能。这是个第三方库,所以要安装的。
使用urllib需要掌握HTTPPasswordMgrWithDefaultRealm,HTTPBasicAuthHandler,bulid_opener,install_opener,等函数的复杂用法,但是Resquests模块,只要一个语句就可以搞定。。。。(不过urllib 写出来的感觉nb 就是了)
Requests 有七个主要方法。
requests.request() (发送一个请求,是其他方法的基础)
r.get() 获取网页的主要方法 r.head() 获取网页头信息 r.post() post请求 r.put() r.pathch() r.delete()
requests.request(method,url,**kwargs)
method:请求方法,对应get post等方法
**kwargs :控制访问的参数,共13个
- params 字典或字节序列,作为参数增加到url中,在访问时就不止访问资源,还能带一些参数让服务器筛选一些资源。
kv = {'key1':'value1','key2':'value2'}
r = requests.request('GET','url',params=kv)
r.url >>>url?key1=value1&key2=value2 #将这些键值对增加到url中
- data: 字典,字节序列或文件对象,作为Request的内容,向服务器提交数据使用
body = '主体部分'
r = requests.request('POST','url',data=body.encode())
- json :JSON格式的数据,作为Request的内容。(在HTTP中最长用的一种格式)
- headers :字典,HTTP定制头,模拟浏览器
- cookie :字典或CookieJar, Request中的cookie
- auth :元组,支持HTTP认证功能
- files :字典类型,传输文件
f={'file' : open('data.xls','rb'}
- timeout : 设置的超时时间,以秒为单位。timeout = 10 超时则报错
- proxies :字典类型,设定访问代理服务器,可以增加登录认证(防止爬虫的逆追踪。。。。)
- .allow_redirects : Ture/Farse 默认true,重定向开关
- stream : 默认true,获取内容立即下载开关
- verify : 默认true,认证SSL证书开关
- cert : 本地SSL证书路径
get() head()等都有这几个参数。
发送get请求
import requests
response = requests.get('https://editor.csdn.net/')
print(response)
>>><Response [200]> #访问成功
header = {'User-Agent': '.....'} #添加请求头,就不像urllib还要创建一个response对象在请求了。
response = requests.get('https://editor.csdn.net/',headers=header)
kw = {'wd':'蔷薇'}
response = requests.get('https://editor.csdn.net/',headers=header,params=kw)
# params 接受一个字典或字符串的查询参数,字典类型自动转换成url编码,不需要格外的urlencode()
# 获取响应的内容
print(resquense.text) #获得字符串的类型,Unicode格式的数据,对content解码后的形式,有可能乱码
print(resquense.content) #获得二进制形式,字节流数据,我们硬盘上网络上都是这种类型的
print(response.url) #获取地址
属性 | 方法 |
---|---|
r.status_code | HTTP请求的返回状态200,404 |
r.encoding | 从HTTP header中猜测的响应内容编码方式 |
r.qpparent_encoding | 从内容中分析出的响应内容(备选编码方式) |
发送POST请求
import requests
url = 'https://i.meishi.cc/login.php?redirect=https%3A%2F%2Fwww.meishij.net%2F'
data = {
'username': '[email protected]',
'password': 'wq15290884759.'
}
resp = requests.post(url,data=data)
print(resp.text)
#当然这样简单的登录只能是一些小网站。。。
使用代理(小号)
只要在请求的方法中(get 或 post )传递个proxies 参数
import requests
proxy = {'http':'111.77.197.127:9999'} #当然这个IP有可能已经挂了。。
url = 'http://www.baidu.com/'
resp = requests.get(url,proxies=proxy) #比urllib的ProxyHandler 好用多了
处理cookie
如果一个响应中包含了cookie,可以利用cookies属性来返回这个cookie值
resp = requests.get('http://www.baidu.com/')
print(resp.cookies) # 获得一个requestscookiejar对象
print(resp.cookies.get_dict()) # 获得字典形式
前文提到的第一种模拟登录的方法,将复制的cookie放在请求头就好:
import requests
url = 'https://www.zhihu.com/hot'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
'cookie':'在你登录界面的cookie复制过来'
}
resp = requests.get(url,headers=headers)
print(resp.text)
session :共享cookie
注意:这里的session不是web开发的那个session,这个地方只是一个会话的对象而已。
对应urllib 库的CookieJar对象。第二种模拟登录方法:
post_url = 'https://i.meishi.cc/login.php?redirect=https%3A%2F%2Fwww.meishij.net%2F'
#登陆界面
post_data = { #不用解码了
'username':'[email protected]',
'password':'wq15290884759.'
}
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}
# 登录
session = requests.session()
session.post(post_url,headers=headers,data=post_data)
# 这个session对象就有了登录账号密码后,服务器发过来的cookie
#访问个人网页
url = 'https://i.meishi.cc/cook.php?id=13686422'
resp = session.get(url) #用有cookie信息的session就可以登录了
print(resp.text)
处理不信任的SSL证书
对于那些已经被信任的SSL证书(SSL证书是数字证书的一种,类似于驾驶证、护照和营业执照的电子副本。因为配置在服务器上,也称为SSL服务器证书)的网站,比如www.baidu.com,使用requests直接就看可以正常的返回响应。
对于那些没有信任的就会报错。
resp = requests.get('https://inv-veri.chinatax.gov.cn/',verify=False) # 将参数verify改成 False 就好
print(resp.content.decode('utf-8'))