python Request模块
Posted mr-l
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Request模块相关的知识,希望对你有一定的参考价值。
---恢复内容开始---
Request的五种请求方式:
- request.get()
- request.post()
- request.head()
- requst.put()
- request.patch()
- request.options()
一:request.get():
源码:
1 def get(url, params=None, **kwargs): 2 r"""Sends a GET request. 3 4 :param url: URL for the new :class:`Request` object. 5 :param params: (optional) Dictionary, list of tuples or bytes to send 6 in the body of the :class:`Request`. 7 :param \\*\\*kwargs: Optional arguments that ``request`` takes. 8 :return: :class:`Response <Response>` object 9 :rtype: requests.Response 10 """ 11 12 kwargs.setdefault(‘allow_redirects‘, True) 13 return request(‘get‘, url, params=params, **kwargs)
参数解析及使用
1 import requests 2 r=requests.request(‘post‘,‘http://www.oldboyedu.com‘,params={‘k1‘:‘python‘}) 3 print(r.url) 4 #https://www.oldboyedu.com/?k1=python
二:request.post()
源码
1 def post(url, data=None, json=None, **kwargs): 2 r"""Sends a POST request. 3 4 :param url: URL for the new :class:`Request` object. 5 :param data: (optional) Dictionary, list of tuples, bytes, or file-like 6 object to send in the body of the :class:`Request`. 7 :param json: (optional) json data to send in the body of the :class:`Request`. 8 :param \\*\\*kwargs: Optional arguments that ``request`` takes. 9 :return: :class:`Response <Response>` object 10 11 :rtype: requests.Response 12 """ 13 return request(‘post‘, url, data=data, json=json, **kwargs)
参数解析及使用
1 b=requests.request(‘post‘,‘http://www.oldboyedu.com‘,data={"k1":‘python‘},json={‘k2‘:"linux"}) 2 print(b.url) 3 print(b.headers) 4 print(b.json()) 5 #由于post提交参数时,不会在url后面加入参数值,所以时看不出效果的 6 7 8 - data: 在请求体里传递的数据 9 10 requests.request( 11 method=‘POST‘, 12 url= ‘http://www.oldboyedu.com‘, 13 params = {‘k1‘:‘v1‘,‘k2‘:‘v2‘}, 14 data = {‘use‘:‘alex‘,‘pwd‘: ‘123‘,‘x‘:[11,2,3]} 15 ) 16 17 请求头: 18 content-type: application/url-form-encod..... 19 20 参数 21 use=alex&pwd=123 22 23 - json 在请求体里传递的数据 24 requests.request( 25 method=‘POST‘, 26 url= ‘http://www.oldboyedu.com‘, 27 params = {‘k1‘:‘v1‘,‘k2‘:‘v2‘}, 28 json = {‘use‘:‘alex‘,‘pwd‘: ‘123‘} 29 ) 30 请求头: 31 content-type: application/json 32 33 参数: 34 "{‘use‘:‘alex‘,‘pwd‘: ‘123‘}"
header参数
1 requests.request( 2 method=‘POST‘, 3 url= ‘http://www.oldboyedu.com‘, 4 params = {‘k1‘:‘v1‘,‘k2‘:‘v2‘}, 5 json = {‘use‘:‘alex‘,‘pwd‘: ‘123‘}, 6 headers={ 7 ‘Referer‘: ‘http://dig.chouti.com/‘, 8 ‘User-Agent‘: "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/56.0.2924.87 Safari/537.36" 9 } 10 )
---恢复内容结束---
以上是关于python Request模块的主要内容,如果未能解决你的问题,请参考以下文章