美文网首页
Python requests库完成接口请求

Python requests库完成接口请求

作者: 测试学习之旅 | 来源:发表于2019-05-08 16:14 被阅读0次

    前言:1. 安装python2/3 (建议Python3)
    2.安装一个PyCharm工具写脚本

    1. 安装requests

    pip install requests
    

    虫师的requests库学习文档

    2. requests是啥?

    3. requests Get请求
    简单的get请求

    import requests
    
    url = "https://www.v2ex.com/api/topics/hot.json"
    # 发送无参数的get请求获取响应结果,响应结果有三种格式html、text、json,默认返回的是html格式
    res = requests.get(url)
    # 获取请求头
    print(res.request.headers)
    # 获取状态码
    print(res.status_code)
    # 获取cookies
    print(res.cookies)
    
    

    带参数的get请求

    import requests
    url = 'https://www.v2ex.com/api/nodes/show.json'
    params = {
        "name":"java"
    }
    res = requests.get(url,params)
    

    发送带cookies的请求

    import requests
    url = "https://www.test/_login"
    params = {'username':'living',
              'password':'123123'}
    res = requests.get(url,params)
    # 获取登陆成功后cookies
    cookies = res.cookies
    # 添加订单接口
    orderurl = 'https://www.test/apply/action/order'
    orderparam = {'phone':1831945110'',
              'orderid':'382761'}
    orderres = requests.get(url,params,cookies=cookies)
    

    发送带定制头的请求

    import requests
    url = 'https://www.v2ex.com/api/nodes/show.json'
    # 参数一般都是以字典格式发送
    params = { "name":"java"}
    herder = {'User-Agent':'Mozilla/6.0'}
    res = requests.post(url,params,herder = herder)
    

    4. requests POST请求

    import requests
    url = ' http://127.0.0.1:8080/test/index/login'
    payparam = {'phone':'1831945110', 'orderid':'382761'}
    res = requests.post(url,params)
    print(res.json())
    

    5. 封装get & post请求

    import requests
    
    class HttpRequest:
        def __init__(self,url,param):
            self.url = url
            self.param = param
    
        def httprequest(self,method,cookies=None):
    
            if method.upper() == 'GET':
                try:
                    res = requests.get(self.url,self.param,cookies=cookies)
                except Exception as e:
                    print("执行get请求报错:",format(e))
                    res = 'Error:get请求报错{0}'.format(e)
            elif method.upper() == 'POST':
                try:
                    res = requests.post(self.url,self.param,cookies=cookies)
                except Exception as e:
                    print("执行post请求报错:",format(e))
                    res = 'Error:post请求报错{0}'.format(e)
    
            else:
                print("错误的请求")
                res = 'Error:错误的请求报错{0}'.format(method)
    
            return res
    
    
        #调用
    if __name__ == '__main__':
        res  = HttpRequest('https://www.v2ex.com/api/nodes/show.json',{'name':'java'}).httprequest('get')
        print(res.json())
    
    
    
    

    相关文章

      网友评论

          本文标题:Python requests库完成接口请求

          本文链接:https://www.haomeiwen.com/subject/vlquoqtx.html