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个方法
局部修改
请求,对应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对象的属性
3.1.2 异常
3.1.3常用框架流程
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个
访问控制参数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('爬取失败')
- requests库
- requests库
- requests库
- requests库
- Requests库
- requests库入门-1-安装requests库
- python requests库 笔记
- Requests库使用
- Requests库的用法
- python requests库介绍
- 爬虫基础----requests库
- Python之requests库
- python安装requests库
- 01.Requests库学习
- Requests库入门
- python库之requests
- Requests库入门
- requests库的安装
- Euler Project : Problem 22
- trie 前缀树
- indexof(str)的用法
- java读取TXT文件的方法
- (个人)AR电子书系统创新实训第二周(1)
- requests库
- heartbeat(尽量保持唯一性存储)和keepalived (尽量保持可用)区别
- 桥接模式的应用
- Libusb开发教程<三> USB设备程序开发
- Linux下用mentohust解决有线锐捷链接问题
- 【codeforces 733E】Sleep in Class 题解
- UVA 548 Tree 【树+DFS】
- SDN在云数据中心的架构
- C++作业5 求和 、数组选择