requests是用python做自动化必须用到的第三方包,需要自己安装,安装命令为:pip install requests,安装完成后,需要导入方可使用,一般使用requests包下面的get方法和post方法,其他不常用
一、requests中的get方法
get方法源码
def get(url, params=None, **kwargs):
r"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return request('get', url, params=params, **kwargs)
可以看到get方法中的参数url是必须传的,params参数默认为None,如果需要可传,重要的是**kwargs,动态参数kwargs可以传其他参数,如cookie,header,verify等特殊参数
一般get方法用法:
import requests
url = "http://webquotepic.eastmoney.com/GetPic.aspx"
params = {"id":"899001_TB","imageType":"FFRS","token":"44c9d251add88e27b65ed86506f6e5da","type":"FFR"}
r =requests.get(url=url,params=params)
print(r.status_code)
print(r.url)
打印结果为:
二、requests中的post方法
post方法源码
def post(url, data=None, json=None, **kwargs):
r"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param 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
:rtype: requests.Response
"""
return request('post', url, data=data, json=json, **kwargs)
从源码中可以看出post方法必要的参数也是url,与get方法不同的是post方法的默认参数多了data和json参数,默认都为None,也包含动态参数**kwargs,在使用post方法的时候,如果除了三个默认参数外,其余参数可使用动态参数,如请求为:http://webquest.jbsh.com/GetPic?name=zhulang$age=20,该请求为post方法,参数data={“id”:“52643”,“pg”:“0”},可按照如下方法使用
import requests
url = "http://webquest.jbsh.com/GetPic"
params = {"name":"zhulang","age":"20"}
data ={"id":"52643","pg":"0"}
r =requests.post(url=url,data=data,params=params)
print(r.url)
打印结果
post方法中data和json有几点需要注意
- 当header为Content-Type: application/x-www-form-urlencoded,或者指定用表单传递参数时,此时用data参数,数据格式为:username=zhu&password=123
- 当header为’Content-Type’: 'application/json’时,用json传递参数,数据格式为:{“username”: “amy”, “password”: “123”}
- 当不指定headers中content-type的类型时,使用data参数传递参数时,content-type默认是:application/json。