request请求的get/post的模块的封装

Posted jacquelineqa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了request请求的get/post的模块的封装相关的知识,希望对你有一定的参考价值。

get是登录请求,post是充值请求,需要登录的cookie.
#利用requests封装get和post请求
import requests
#不论是get,post请求都需要url,data(传递参数,mobilephone,pwd,amount),cookies,get里没有cookies,
# 我们在response里添加一个cookie=None,这样get和post请求格式和内容就差不多相似,
# 创建一个类class
class HttpRequest:
def http_request(self,url,data,method,cookie=None):
#url,data,cookis都可以参数化
if method==‘get‘:
res = requests.get(url, data, cookies=cookie)
else:
res=requests.post(url,data,cookies=cookie)
print("响应正文: ",res.json())
return res

if __name__ == ‘__main__‘:
url = ‘http://test.lemonban.com/futureloan/mvc/api/member/login‘
data = {"mobilephone": "18688773467", "pwd": "123456"}
res=HttpRequest().http_request(url,data,‘post‘)#把url,data传进来,cookie默认为none
print("登录结果是: ", res.json())
#充值
recharge_url=‘http://test.lemonban.com/futureloan/mvc/api/member/recharge‘
recharge_data={"mobilephone":"18688773467","amount":"1000"}
recharge_res = HttpRequest().http_request(recharge_url,recharge_data,‘get‘,res.cookies)
print("充值结果是: ", recharge_res.json())



#https 请求:request.get(url,data,verify=false)


找了其他网站练习

import requests

class HttpRequest:
def http_request(self,url,data,method,cookie=None):
if method==‘get‘:
res = requests.get(url, data, cookies=cookie)
else:
res=requests.post(url,data,cookies=cookie)
print("响应正文: ",res.json())
return res

if __name__ == ‘__main__‘:
url = ‘http://v.juhe.cn/laohuangli/d‘
data = {"key": "XXXXX", "date": "2020-4-11"}
res=HttpRequest().http_request(url,data,‘post‘)
print("post结果是: ", res.json())
get_res = HttpRequest().http_request(url, data, ‘get‘, res.cookies)
print("get结果是: ", res.json())


另外一个网站

import requests

class HttpRequest:
def http_request(self,url,data,method,cookie=None):
if method==‘get‘:
res = requests.get(url, data, cookies=cookie)
else:
res=requests.post(url,data,cookies=cookie)
print("响应正文: ",res.json())
return res

if __name__ == ‘__main__‘:
url = ‘http://v.juhe.cn/toutiao/index‘
data = {"key": "XXXXXXX ", "type": "guonei"}
res=HttpRequest().http_request(url,data,‘post‘)
print("post结果是: ", res.json())
get_res = HttpRequest().http_request(url, data, ‘get‘, res.cookies)
print("get结果是: ", res.json())


以上是关于request请求的get/post的模块的封装的主要内容,如果未能解决你的问题,请参考以下文章

Request/Response;post/get

封装GET/ POST请求

python的requests模块

Python接口自动化之request请求封装

Python爬虫笔记(二)requests模块get,post,代理

Python接口自动化之requests请求封装