1.Get Request Premise: requests Library is a third-party library of Python, need to be installed in advance oh, you can directly use the PIP command: ' python–m pip install requests ' by convention, First, print the properties of the requests library to see which properties. >>> Import requests>>> dir (requests) #查看requests库的属性 [' connectionerror ', ' httperror ', ' Nullhandler ', ' preparedrequest ', ' Request ', ' requestexception ', ' Response ', ' Session ', ' Timeout ', ' toomanyredirects ', ' urlrequired ', ' __author__ ', ' __build__ ', ' __builtins__ ', ' __copyright__ ', ' __doc__ ', ' __file__ ', ' __license__ ', ' __ name__ ', ' __package__ ', ' __path__ ', ' __title__ ', ' __version__ ', ' Adapters ', ' API ', ' auth ', ' certs ', ' Codes ', ' Compat ', ' C Ookies ', ' delete ', ' exceptions ', ' Get ', ' head ', ' hooks ', ' logging ', ' models ', ' options ', ' Packages ', ' Patch ', ' post ', ' Put ', ' request ', ' session ', ' Sessions ', ' status_codes ', ' structures ', ' utils '] so you can see requests properties get,post,delete, Put, which corresponds to the method of the HTTP request. is commonly used for get and post requests. A GET request is typically a query for resource information. Post is typically updated with resource information. 1.1 Viewing the use of Get functions >>> Help (requests.get) #查看requests库的属性get请求函数的使用 &NBsp Help on function get in module requests.api: get (URL, Params=none, **kwargs) sends a get request. :p aram ur L:url for the New:class: ' Request ' object. :p Aram params: (optional) Dictionary or bytes to being sent in T He query string for The:class: ' request ' . :p Aram \*\*kwargs:optional arguments ' request ' Takes. :return :: Class: ' Response <Response> ' object :rtype:requests. response 1.2 requests of the GET function of the url: the URL address of the calling interface. params: As an optional parameter, this parameter is a dictionary type. The data is placed in the URL in the form of a key/value pair followed by a question mark. For example, if R=requests.get ("Http://httpbin.org/get", params={' key1 ': ' value1 ', ' key2 ': ' value2 '}), then the destination URL for the final request is http:// bin.org/get?key1=val1& Key2=val2. **kwargs: Other optional parameters, such as Headers,files,cookies,auth,timeout,json. Example: auth= (' username, ' password '): User authentication used in interface security testing. Example: headers = {' user-agent ': ' my-app/0.0.1 '}: can be customized to send the request header. The return value of the 1.3 requests function (HTTP response) Returns the Response class object (Requests.models.Response). Response class >& from the requests module models.pyGt;> r=requests.get (' http://httpbin.org/get ') #查看response的属性 >>> dir (r) [' __attrs__ ', ' __ Bool__ ', ' __class__ ', ' __delattr__ ', ' __dict__ ', ' __doc__ ', ' __format__ ', ' __getattribute__ ', ' __getstate__ ', ' __hash_ ' _ ', ' __init__ ', ' __iter__ ', ' __module__ ', ' __new__ ', ' __nonzero__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __ Setattr__ ', ' __setstate__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ ', ' _content ', ' _content_ Consumed ', ' apparent_encoding ', ' close ', ' connection ', ' content ', ' cookies ', ' elapsed ', ' encoding ', ' headers ', ' history ', ' is_permanent_redirect ', ' is_redirect ', ' iter_content ', ' iter_lines ', ' json ', ' links ', ' OK ', ' raise_for_status ', ' Raw ', ' reason ', ' request ', ' status_code ', ' text ', ' URL '] the properties commonly used for returning objects are as follows: json (): Method for generating JSON data objects. If the JSON decoding fails, R.json throws an exception. For example, the response content is 401 (unauthorized), and attempting to access R.json will throw Valueerror:no JSON object could be decoded exception. Status_code: Response status code. encoding: encoding, such as Utf-8. url: Destination URL. headers: Response header. Typeis a dictionary type and returns none if the key does not exist. text: Response content. String, it is automatically decoded based on the character encoding of the response header. If you change the encoding r.encoding, the Request will use the new value of r.encoding whenever you visit r.text. Content: Binary response contents. Byte way, will automatically decode for you gzip and deflate compression. RAW: The original response content, which is Urllib's response object, is stream=true in the request, and then read with R.raw.read (). R.raise_for_status: Failed request (not 200 response) throws an exception. 1.4 illustration >>> payload={' key1 ': ' value1 ', ' key2 ': ' value2 '} >>> r= Requests.get ("Http://httpbin.org/get", Params=payload) >>> r.status_code 200 >> > R.json () {u ' origin ': U ' 113.98.252.236 ', U ' headers ': {u ' Host ': U ' httpbin.org ', U ' accept-encoding ': U ' gzip, Deflate ', U ' Accept ': U ' */* ', U ' user-agent ': U ' python-requests/2.7.0 cpython/2.7.11 windows/7 '}, U ' args ': {u ' key2 ': U ' Value2 ', U ' key1 ': U ' value1 '}, u ' url ': U ' http://httpbin.org/get?key2=value2&key1=value1 '} >>> R.url #url: The params data is placed in the URL in the form of a key/value pair followed by a question mark. u ' http://httpbin.org/get?key2=value2&key1=value1 ' >>> r.headers {' contEnt-length ': ' 334 ', ' server ': ' Nginx ', ' connection ': ' keep-alive ', ' access-control-allow-credentials ': ' true ', ' Date ': ' Fri, 09:04:40 GMT ', ' access-control-allow-origin ': ' * ', ' content-type ': ' Application/json '} >>& Gt r.headers[' Content-type '] ' Application/json ' >>> r.raw < Requests.packages.urllib3.response.HTTPResponse object at 0x0000000002e64e10> >>> r.cookies <RequestsCookieJar[]> >>> r.text u ' {\ n ' args ': {\ n ' key1 ': ' value1 ', \ n ' key2 ': ' value2 ' \ n}, \ N "headers": {\ n "Accept": "*/*", \ n "accept-encoding": "gzip, deflate", \ n "Host": "httpbin.org", \ n "user-agent": "Pytho n-requests/2.7.0 cpython/2.7.11 Windows/7 "\ n}, \ n" origin ":" 113.98.252.236 ", \ n" url ":" Http://httpbin.org/get?key2= Value2&key1=value1 ' \n}\n ' >>> r.content ' {\ n ' args ': {\ n ' key1 ': ' value1 ', \ n ' key2 ': ' value2 ' \ n}, \ n "headers": {\ n "Accept": "*/*", \ n "accept-encoding": "gzip, deflate", \ n"Host": "httpbin.org", \ n "user-agent": "python-requests/2.7.0 cpython/2.7.11 Windows/7" \ n}, \ n "origin": " 113.98.252.236 "\ n" url ":" Http://httpbin.org/get?key2=value2&key1=value1 "\n}\n ' >>> payload = {' Key1 ': ' value1 ', ' key2 ': ' value2 '} >>> r = Requests.get ("Http://httpbin.org/get", Params=payload,stream =true) >>> R.raw <requests.packages.urllib3.response.httpresponse object at 0x0000000003105940> >>> r.raw.read () ' {\ n ' args ': {\ n ' key1 ': ' value1 ', \ n ' key2 ': ' value2 ' \ n}, \ N "headers": {\ n "Accept": "*/*", \ n "accept-encoding": "gzip, deflate", \ n "Host": "httpbin.org", \ n "user-agent": "Pytho n-requests/2.7.0 cpython/2.7.11 Windows/7 "\ n}, \ n" origin ":" 113.98.252.236 ", \ n" url ":" Http://httpbin.org/get?key2= Value2&key1=value1 "\n}\n ' 1.6 GET request summary sum up, through Requests.get (" A URL ", params={dictionary type parameter key value pair}) Simulate the browser sending an HTTP request (where the requested method is get, the URL of the request is the following form of Http://httpbin.org/get?). key2=value2&key1=value1), serverWhen the data is processed, a response object is returned, and by reading the property values of the response object, such as JSON data, a series of assertions can be made to verify that the data returned by the interface is correct. 2.post Request ## 2.1 View post function Usage >>> help (requests.post) # View the properties of the Requests library POST request function using post (URL, Data=none, Json=none, **kwargs) sends a post request. :p Aram URL: URL for the New:class: ' Request ' object. :p Aram data: (optional) Dictionary, Bytes, or File-like object to send in th E Body of The:class: ' Request ' . :p Aram JSON: (optional) JSON data to send in the body of The:class: ' request '. : param \*\*kwargs:optional arguments that ' request ' Takes. :return:: Class: ' Response <Response> ' object& Nbsp;:rtype:requests. response 2.2 requests of the Post function url: The URL address of the calling interface. data: As an optional parameter, this parameter is a dictionary type. json: As an optional parameter, this parameter is a JSON type. **kwargs: Other optional parameters, such as headers. 2.3 Return value of requests function (HTTP response) same as 1.3 json (): Method for generating JSON data objects. If the JSON decoding fails, R.json throws an exception. For example, the response content is 401 (unauthorized), and attempting to access R.json will throw Valueerror:no JSON object could Be decoded exception. status_code: Response status code. encoding: encoding, such as Utf-8. url: Destination URL. headers: Response header. The type is a dictionary type, and none is returned if the key does not exist. text: Response content. String, it is automatically decoded based on the character encoding of the response header. If you change the encoding r.encoding, the Request will use the new value of r.encoding whenever you visit r.text. content: Binary response content. Byte way, will automatically decode for you gzip and deflate compression. raw: The original response content, that is, urllib response object, the request to add stream=true, and then use R.raw.read () read. r.raise_for_status: Failed request (not 200 response) throws an exception. 2.4 Illustration >>> payload = {' Key1 ': ' value1 ', ' key2 ': ' value2 '} >>> r = Requests.post ("Http://httpbin.org/post", Data=payload) >>> r.status_code 200 >>> R.json () {u ' files ': {}, U ' origin ': U ' 113.98.252.236 ', U ' form ': {u ' key2 ': U ' value2 ', U ' key1 ': U ' Value1 '}, u ' url ': U ' http://httpbin.org/post ', U ' args ': {}, U ' headers ': {u ' content-length ': U ' ", U ' accept-encoding ': u ' Gzip,deflate ', U ' Accept ': U ' */* ', U ' user-agent ': U ' python-requests/2.7.0 cpython/2.7.11 windows/7 ', U ' Host ': U ' Httpbin. org ', u ' content-type ': U ' application/x-www-form-urlencoded '}, U ' json ': None, U ' data ': U '} >>> R.url u ' http://httpbin.org/post ' >>> r.headers {' content-length ': ' 461 ', ' server ': ' Nginx ', ' connection ': ' keep-alive ', ' access-control-allow-credentials ': ' true ', ' Date ': ' Mon, DEC 2016 02 : 46:14 GMT ', ' access-control-allow-origin ': ' * ', ' content-type ': ' Application/json '} >>> r.headers[' Content-type '] ' Application/json ' >>> r.raw < Requests.packages.urllib3.response.HTTPResponse object at 0x0000000002ee4a58> >>> r.text u ' {\ n ' args ': {}, \ n ' Data ': "", \ n "files": {}, \ n "form": {\ n "key1": "value1", \ n "key2": "value2" \ n}, \ n "Heade Rs ": {\ n" Accept ":" */* ", \ n" accept-encoding ":" gzip, deflate ", \ n" content-length ":" All ", \ n" content-type ":" Applicatio N/x-www-form-urlencoded "\ n" Host ":" httpbin.org ", \ n" user-agent ":" Python-requests/2.7.0 cpython/2.7.11 Windows/7 "\ n}, \ n" JSON ": null, \ n" origin ":" 113.98.252.236 ", \ n" url ":" Http://httpbin.org/post "\ n}\n ' >>> r.content ' {\ n ' args ': {}, \ n ' data ': ', \ n ' files ': {}, \ n ' form ': {\ n ' key1 ': ' value1 ', \ n "Key2": "value2" \ n}, \ n "headers": {\ n "Accept": "*/*", \ n "accept-encoding": "gzip, deflate", \ n "content-length": "23" , \ n "content-type": "application/x-www-form-urlencoded", \ n "Host": "httpbin.org", \ n "user-agent": "python-requests/ 2.7.0 cpython/2.7.11 Windows/7 "\ n}, \ n" JSON ": null, \ n" origin ":" 113.98.252.236 ", \ n" url ":" Http://httpbin.org/post "\ n }\n ' >>> payload = {' Key1 ': ' value1 ', ' key2 ': ' value2 '} #获取原始响应内容 >>> r = Requests.post ("Http://httpbin.org/post", data=payload,stream=true) >>> r.raw < Requests.packages.urllib3.response.HTTPResponse object at 0x0000000003105208> >>> r.raw.read () ' {\ n ' args ': {}, \ n ' data ': ', ' \ n ' files ': {}, \ nthe ' form ': {\ n "key1": "value1", \ n "key2": "value2" \ n}, \ n "headers": {\ n "Accept": "*/*", \ n "accept-encoding": "gzip, deflate", \ n "content-length": "All", \ n "content-type": "application/x-www-form-urlencoded", \ n "Host": "httpbin.org", \ n " User-agent ":" python-requests/2.7.0 cpython/2.7.11 Windows/7 "\ n}, \ n" JSON ": null, \ n" origin ":" 113.98.252.236 ", \ n" url ":" Http://httpbin.org/post "\n}\n #使用 JSON parameter direct delivery >>> payload = {' Key1 ': ' value1 ', ' key2 ': ' value2 ' } >>> r = requests.post ("Http://httpbin.org/post", json=payload) >>> r.text u ' {\ n ' Args ": {}, \ n" Data ":" {\ \ "key2\\": \ \ "value2\\", \ \ "key1\\": \ \ "value1\\"} "\ n" Files ": {}, \ n" form ": {}, \ n" Headers ": {\ n "Accept": "*/*", \ n "accept-encoding": "gzip, deflate", \ n "content-length": "$", \ n "content-type": "Application/js On "\ n" Host ":" httpbin.org ", \ n" user-agent ":" python-requests/2.7.0 cpython/2.7.11 Windows/7 "\ n}, \ n" json ": {\ n" key1 ":" value1 ", \ n" key2 ":" value2 "\ n}, \ n"Origin ":" 113.98.252.236 ", \ n" url ":" Http://httpbi 3. Other usages 3.1 custom request Header >>> payload = {' Key1 ': ' value1 ', ' key2 ': ' value2 '} >>> headers = {' user-agent ': ' my-app/0.0.1 '} >>> r = Requests.post ("Http://httpbin.org/post", data=payload,headers=headers) 3.2 Uploading Files >>> import os >>> os.getcwd () ' d:\\pythontest ' >>> f=open (' 1.txt ', ' w+ ') >>> f.write (' test ') >>> os.listdir (' d:\\pythontest ') [' 1.txt ',] >>> import requests >>> url = ' Http://httpbin.org/post ' >>> files = { ' File ': Open (' 1.txt ', ' RB ')} >>> r = requests.post (URL, files=files) >>> r.text u ' {\ N "args": {}, \ n "Data": "", \ n "files": {\ n "file": "\ n}, \ n" form ": {}, \ n" headers ": {\ n" Accept ":" */* ", \ n" accept- Encoding ":" gzip, deflate ", \ n" content-length ":" 141 ", \ n" content-type ":" MultipArt/form-data; Boundary=37de3eb22a754f34849771891b77bd23 "\ n" Host ":" httpbin.org ", \ n" user-agent ":" python-requests/2.7.0 CPython /2.7.11 Windows/7 "\ n}, \ n" JSON ": null, \ n" origin ":" 113.98.252.236 ", \ n" url ":" Http://httpbin.org/post "\n}\n" 3. 3 send >>> URL of cookies = ' http://httpbin.org/cookies ' >>> cookies = dict (cookies_are= ' Working ') >>> r = Requests.get (URL, cookies=cookies) >>> r.text u ' {\ n ' cookies ': {\ N "cookies_are": "Working" \ n}\n}\n ' 4. Knowledge expansion 4.1 about the difference between get and post get the requested data is appended to the URL (that is, Put the data in the HTTP protocol header), to split the URL and transfer data, the parameters are connected to &, such as:login.action?name=hyddd& password=idontknow&verify=%e4%bd% A0%E5%A5%BD. If the data is an English letter/number, sent as is, if it is a space, converted to +, if it is Chinese/other characters, the string is directly encrypted with BASE64, such as:%E4%BD%A0%E5%A5%BD, where the xx in%xx is the symbol in 16 binary notation ASCII. post submits the data in the packet that is the HTTP packet. 4.2 accept-encoding Description of the requested headers Accept-encoding in the client item in the headers of the request, for example accept-encoding: gzip, deflate. The browser declares that it has receivedThe encoding method, which typically specifies the compression method, whether compression is supported, what compression method is supported (note: This is not a gzip,deflate encoding). 4.3 the Content-type description of the headers of the response content-type is a very important part of the return message, indicating what MIME type the subsequent document belongs to. content-type: [Type]/[subtype]; Parameter For example, the most common is text/html, which means that the returned content is a text type, and this text is in HTML format. In principle, the browser will decide how to display the returned message body content according to Content-type. ype has the following form: text: A text message that is used in a standardized manner, text messages can be of multiple character sets and or multiple formats; multipart: Multiple parts used to connect the body of a message form a message. These parts can be different types of data; application: Used to transfer application data or binary data; message: Used to wrap an e-mail message; Image: Used for transmitting static picture data; audio: For transmitting audio or sound data; video: For transmitting dynamic image data, which can be a video data format with audio editing. The subtype is used to specify the detailed form of the type. parameter can be used to specify additional information, and in more cases, charset parameters that specify the way text is encoded, such as Text/plain and text/htm. Note: If you want to do Web Automation interface testing, you must understand the HTTP protocol, want to know more HTTP protocol, can view the HTTP protocol in detail to the 4.4 about requests data related address Document address:http://docs.python-requests.org/en/master/ Chinese document address: http://cn.python-requests.org/zh_CN/latest/
Python web interface Automation test requests library detailed