requests库请求

请求requests

参考:

http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced

首先要导入:import requests
r = requests.post('http://httpbin.org/post', data=payload) #post请求,参数格式为from
r = requests.post('http://httpbin.org/post', json=payload) #post请求,参数格式为json

r = requests.get('http://httpbin.org/get') #单纯的GET请求
r = requests.get("http://httpbin.org/get", params=payload) #带参数的get请求
r = requests.get('https://api.github.com/some/endpoint', headers={'user-agent': 'my-app/0.0.1'}) #带头参数的get请求
r = requests.get('http://github.com', timeout=0.001) #带超时判断的get请求
r = requests.get('http://httpbin.org/cookies', cookies=cookies) #带cookies参数的get请求

其他:
>>> r = requests.put('http://httpbin.org/put', data = {'key':'value'}) #从客户端向服务器传送的数据取代指定的文档的内容
>>> r = requests.delete('http://httpbin.org/delete') #请求服务器删除指定的页面
>>> r = requests.head('http://httpbin.org/get') #只请求页面的首部
>>> r = requests.options('http://httpbin.org/get')


返回内容还有其它更多信息
-- r.url # 获取url
-- r.text #字符串方式的响应体,会自动根据响应头部的字符编码进行解码
-- r.encoding #编码格式,可以用r.encoding = 'utf-8'来定义编码格式
-- r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩.py3是r.content.decode
-- r.json() #Requests中内置的JSON解码器
-- r.raw #返回原始响应体,请求里添加stream=True属性

-- r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
-- r.cookies #获取cookie

-- r.status_code #响应状态码
-- r.raise_for_status() #失败请求(非200响应)抛出异常


文件上传:
使用files参数,files指向一个dict字典,字典的键是'文件名',而值是打开这个文件读取到内存的内容。一般用post请求
例子:
cur_path = os.path.dirname(os.path.realpath(__file__)) #获得所引用的模块 所在的绝对路径
filePath = os.path.join(cur_path + r"imgs4.jpg") #组成一个绝对路径
files = {'companyLogo': open(filePath, 'rb')} #files字典
headers = {'Content-Disposition': 'form-data'}
r = requests.post(SaveImg.host + SaveImg.url + '/saveImg', files=files, headers=headers)

文件下载
使用stream = True控制下载动作,获取字节content用write方法把下载内容写入path这个路径里面
url = 'http://docs.python-requests.org/zh_CN/latest/_static/requests-sidebar.png'
path = 'C:/Users/ms/Downloads/test.jpg'
r = requests.get(url,stream = True)
with open(path,'wb') as f: #创建一个上下文管理器对象f,执行f.write(r.content),不管是否报错最后都会释放资源
f.write(r.content) #相当于try:finally:

重定向状态码:
--301 redirect: 301 代表永久性转移(Permanently Moved)
--302 redirect: 302 代表暂时性转移(Temporarily Moved )
重定向地址放在head返回信息的:Location里面
r = s.get('https://i.cnblogs.com/EditPosts.aspx?opt=1',
headers=headers,
# allow_redirects=True, #启动重定向
allow_redirects=False, #关闭重定向
verify=False,
)
print(r.history) #使用r.history查看重定向历史

获取cookie
直接调用r.cookies即可得到返回值
获取cookie的某一个值:r.cookies['NID']

消除警告信息
from requests.packages import urllib3
urllib3.disable_warnings() #这条命令主要用于消除警告信息

代理设置

在进行爬虫爬取时,有时候爬虫会被服务器给屏蔽掉,这时采用的方法主要有降低访问时间,通过代理ip访问,
如下:

import requests

proxies = {
"http": "http://127.0.0.1:9743",
"https": "https://127.0.0.1:9743",
}


response = requests.get("https://www.taobao.com", proxies=proxies)
print(response.status_code)
ip可以从网上抓取,或者某宝购买

如果代理需要设置账户名和密码,只需要将字典更改为如下:
proxies = {
"http":"http://user:password@127.0.0.1:9999"
}
如果你的代理是通过sokces这种方式则需要pip install "requests[socks]"
proxies= {
"http":"socks5://127.0.0.1:9999",
"https":"sockes5://127.0.0.1:8888"
}

认证设置

如果碰到需要认证的网站可以通过requests.auth模块实现
response = requests.get("http://120.27.34.24:9001/",auth=("user","123"))
print(response.status_code)

原文地址:https://www.cnblogs.com/lijinglj/p/9646159.html