Python can use the Urllib module to request a Web site, or interface, but the Urllib module is too troublesome, pass parameters, all have to be bytes type, return data is also bytes type, but also to decode, want to directly return the results to use, but also with JSON, Send GET request and POST request, also do not pass, use more trouble, there is a more convenient module, more convenient than urllib module, is the requests module, it is more convenient to use, need to install, Pip install requests can, The following is an example of a requests module
Import Requests pay_url = ' Http://szz.nnzhp.cn/pay ' balance_url = ' http://szz.nnzhp.cn/get_balance ' balance_data = {' user_id ':1} pay_data ={"user_id":1,"Price":"999"} balance_res = requests. Get(balance_url,balance_data). Text #发送get请求, and gets the result returned, the text gets the result of a stringPrint(balance_res) balance_res = requests. Get(balance_url,balance_data). JSON() #发送get请求, and gets the result returned, the JSON () method gets the result directly as a dictionaryPrint(balance_res) pay_res = requests. Post(pay_url,pay_data). JSON()#调用post方法 Print(pay_res) #==== entry is the = = = of the JSON stringURL = ' Http://api.nnzhp.cn/getmoney ' Data = {"userid":1} res = requests. Post(URL,json=data). JSON()#指定入参json Print(res) #====== Adding cookie===== URL = ' Http://api.nnzhp.cn/setmoney2 ' Data = {' userid ':1,' money ':9999} Cookie = {' token ':' token12345 '} res = requests. Post(URL,data,cookies=cookies). JSON()#使用cookies参数指定cookie Print(res) #===== Add permission validation =====URL = ' Http://api.nnzhp.cn/setmoney ' Data = {' userid ':1,' money ':91999} res = requests. Post(URL,data,auth=(' admin ',' 123456 ')). JSON() #使用auth参数指定权限验证的账号密码, Auth is a tuple. Print(res) #====== sending files =====URL = ' http://api.nnzhp.cn/uploadfile ' res = requests. Post(url,files={' file ':open(' api11.py ')}) . JSON() #指定files参数, pass a file, is a file object Print(res) #===== Send header======URL = ' http://api.nnzhp.cn/getuser2 ' Data = {' userid ':1} header = {' content-type ': 'application/json '} res = requests. Post(URL,headers=header). JSON() #指定headers参数, add headersPrint(res)
Welcome to share reprint
Python network programming, requests module