python requests use

Requests are using third-party libraries written in python, based urllib, using Apache2 Licensed open-source HTTP protocol library. It is more convenient than urllib, HTTP fully meet the test requirements for multi-interface testing, in order to apply to work in the future I began learning
Reference Source: https://www.jianshu.com/p/d78982126318

First, install third-party libraries

pip install requests

Secondly, the use requests

import requests

Some common methods Request Library

1.requests.request(method,url,**kwargs)

Construct and send a Request object returns a Response object, the supporting basis of the method of the methods

method: to use the new HTTP Request object methods, including: GET, POST, PUT, DELETE, etc.
url: new Request object URL link
** kwargs: 13 optional parameter access control

(1) params: byte dictionary or a sequence, as a parameter added to the url

paramsValue={'key1':'value1','key2':'value2'}
r=requests.request('GET','http://www.baidu.com',params=paramsValue)
print(r.url)
#执行结果:http://www.baidu.com/?key1=value1&key2=value2;若paramsValue为字符串,结果相仿

(2) data: dictionary, a sequence of bytes, the file as the contents of the Request object body

#字典
dataDicValue={'key1':'value1','key2':'value2'}
r=requests.request('GET','http://www.baidu.com',data=dataDicValue)
#字节序列
dataStrValue='test'
r=requests.request('GET','http://www.baidu.com',data=dataStrValue)
#文件
dataFileValue={'file':open('test.csv','rb')}
r=requests.request('POST','http://www.baidu.com',data=dataFileValue)

(3) json: JSON-formatted data, as the contents of the Request object body

jsonValue={'key1':'value1','key2':'value2'}
r=requests.request('POST','http://www.baidu.com',json=jsonValue)

(4) headers: dictionary format, HTTP request header, a content of the Request object Header

headerValue={'user-agent': 'Chrome/10'}
r=requests.request('POST','http://www.baidu.com',headers=headerValue)
print(r.headers)
#{'Accept-Ranges': 'bytes', 'Cache-Control': 'max-age=86400', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Length': '4867', 'Content-Type': 'text/html', 'Date': 'Wed, 15 Aug 2018 10:22:42 GMT', 'Etag': '"3dcd-560eb5cea6700"', 'Expires': 'Thu, 16 Aug 2018 10:22:42 GMT', 'Last-Modified': 'Fri, 22 Dec 2017 10:34:36 GMT', 'P3p': 'CP=" OTI DSP COR IVA OUR IND COM "', 'Server': 'Apache', 'Set-Cookie': 'BAIDUID=6AE11C63536CF472F9B403B1BE467161:FG=1; expires=Thu, 15-Aug-19 10:22:42 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1', 'Vary': 'Accept-Encoding,User-Agent'}

(5) cookies: a dictionary or CookieJar, Request of cookie

#字典
cookieDicValue={'key1':'value1','key2':'value2'}
r=requests.request('POST','http://www.baidu.com',cookies=cookieDicValue)
print(r.cookies)
#<RequestsCookieJar[]>
#CookieJar
cookiesJarValue=cookiejar.CookieJar()
r=requests.request('POST','http://www.baidu.com',cookies=cookiesJarValue)
print(r.cookies)
#<RequestsCookieJar[]>

(6) files: the dictionary, the form {filename: fileobject}, represents a plurality of portions to be uploaded

filesValue = {'file': open('test.csv', 'rb')}
r = requests.request('POST', 'http://www.baidu.com', files=filesValue)

(7) auth: Auth or handle (user, pass) tuple

#Auth
authBasicValue=HTTPBasicAuth('username','password')
r = requests.request('POST', 'http://www.baidu.com', auth=authBasicValue)
#(user,pass)元组
authTupValue=('username','password')
r=requests.request('POST','http://www.baidu.com',auth=authTupValue)

(8) timeout: server data waiting timeout limit, is a float or a (connect timeout, read timeout) tuple

#浮点数(单位秒)
timeoutFloatValue=12
r=requests.request('POST','http://www.baidu.com',timeout=timeoutFloatValue)
#(connect timeout, read timeout) 元组;
#connect timeout:建立连接所用的时间;适用于网络状况正常的情况下,两端所用的时间
#readtimeout:建立连接后从服务器读取到可用资源所用的时间;正常情况下,当我们发出请求时可以收到请求的结果,也就是页面上展示的内容,但是当网络状况很差的时候,就会出现页面上无法展示出内容的情况。另外当我们使用爬虫或者其他全自动的程序时,无法判断当前的网络状况是否良好,此时就有了ReadTimeout的用武之地了,通过设置ReadTimeout参数
#注意:在我们使用需要设置这两项参数的服务或程序时,应该对两项参数一起设置。 一般而言两项参数的数值可以设置成一样的,但可以把ReadTimeout设置的长一点,ConnectTimeout可以相对比较短,这是源于我们的网络状况一般较为稳定,连接时很少出现问题,但是读取时因为数据下载时的网络波动,出状况的可能性更大一些。
timeoutTupValue=(10,25)
r=requests.request('POST','http://www.baidu.com',timeout=timeoutTupValue)

(9) allow_redirects: True / False, the default is Ture, redirection switch indicates allowing POST / PUT / DELETE redirection method to True

#禁止重定向
r=requests.request('POST','http://www.baidu.com',allow_redirects=False)

(10) proxies: a dictionary, used to map protocol proxy URL

#以下是根据不同协议选择不同代理,也可以使用list+随机方式使用多个代理地址访问URL
poxiesValue={'http':'xxx.xxx.xxx.xxx:xx','https':'xxx.xxx.xxx.xxx:xx'}
r=requests.request('POST','http://www.baidu.com',poxies=poxiesValue)

(11) verify: True / False, True default, switch SSL certificate authentication; to True will verify the SSL certificate cert parameter may be used to provide a path CA_BUNDLE; is False, SSL authentication is ignored

#忽略SSL验证
r=requests.request('POST','http://www.baidu.com',varify=False)

(12) stream: True / False, True default, immediately obtain download switch body, in response to False will download its head and body response; to True response header will be downloaded, only when the call Reponse content download method body in response to

# stream为True时下载步骤
#stream设置为True,直接下载响应头
r=requests.request('POST','http://www.baidu.com',stream=True)
#调用content方法下载响应体
r.content

(13) cert: when a string is the path SSL client certificate file (.pem format, the file path includes keys and certificates), if a tuple, it should be a ( 'cert', 'key') bins for

#文件路径
requests.request('POST','http://www.baidu.com',cert='/True_path/server.pem')
#元组
certTupValue=('/value/value.cert','/value/key')
requests.request('POST','http://www.baidu.com',cert=certTupValue)

2.requests.get (url, params = None, ** kwargs)
Request URL locations of the resource

url: Object Request new URL link
params: byte dictionary or a sequence, as a parameter added to the url
** kwargs: 12 Optional access control parameters (in addition to the other with a params)

3.requests.head (url, ** kwargs)
Request resource URL location report response message, i.e., the header information obtained in response to the resource

url: the new Request object URL link
** kwargs: 13 access control parameters (with 1)

4.requests.post (url, data = None, json = None, ** kwargs)
after the request for the additional resources to the new URL location data

url: Object Request new URL link
data: dictionary, a sequence of bytes, the file as the contents of the Request object body
json: JSON-formatted data, as the contents of the Request object body
** kwargs: 11 access control parameters (except Data, other external json with 1)

5.requests.put (url, data = None, ** kwargs)
request to a resource URL stored position, covering the original URL resource location

url: Object Request new URL link
data: dictionary, a sequence of bytes, the file as the contents of the Request object body
** kwargs: 12 access control parameters (in addition to other data the same 1)

6.requests.patch (url, data = None, ** kwargs)
requests a resource URL partial update position, i.e. where the changing part of the resource

url: Object Request new URL link
data: dictionary, a sequence of bytes, the file as the contents of the Request object body
** kwargs: 12 access control parameters (in addition to other data the same 1)

7.requests.delete (url, ** kwargs)
a request to delete the URL location of storage resources

url: the new Request object URL link
** kwargs: 13 access control parameters (with 1)



Author: nzdnllm
link: https: //www.jianshu.com/p/c7b25bc3520e
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.

Published 17 original articles · won praise 2 · views 20000 +

Guess you like

Origin blog.csdn.net/toove/article/details/97370001