首页 > 代码库 > python接口自动化8-参数化

python接口自动化8-参数化

前言

前面一篇实现了参数的关联,那种只是记流水账的完成功能,不便于维护,也没什么可读性,接下来这篇可以把每一个动作写成一个函数,这样更方便了。

参数化的思维只需记住一点:不要写死

一、登录函数

1.s参数是session的一个实例类,先放这里,方便写后面代码

2.登录函数传三个参数,s是需要调用前面的session类,所以必传,可以传个登录的url,然后payload是账号和密码

技术分享

二、保存草稿

1.编辑内容的标题title和正文body_data参数化了,这样后面可以方便传不同值

2.这里返回了获取到新的url地址,因为后面的postid参数需要在这里提取

技术分享

 

三、提取postid

1.这里用正则表达式提取url里面的postid

技术分享

 

四、删除草稿

1.传个url和postid就可以了

技术分享

 

五、参考代码:

# coding:utf-8
import requests

def login(s, url, payload):
    ‘‘‘登录‘‘‘
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
               "Accept": "application/json, text/javascript, */*; q=0.01",
               "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
               "Accept-Encoding": "gzip, deflate, br",
               "Content-Type": "application/json; charset=utf-8",
               "X-Requested-With": "XMLHttpRequest",
               "Content-Length": "385",
               "Cookie": "xxx已省略",
               "Connection": "keep-alive"
               }
    r = s.post(url, json=payload, headers=headers, verify=False)
    result = r.json()
    print result
    return result[‘success‘]    # 返回True或False

def save_box(s, url2, title, body_data):
    ‘‘‘# 获取报存之后url地址‘‘‘
    body = {"__VIEWSTATE": "",
        "__VIEWSTATEGENERATOR": "FE27D343",
        "Editor$Edit$txbTitle": title,
        "Editor$Edit$EditorBody": "<p>"+body_data+"</p>",
        "Editor$Edit$Advanced$ckbPublished": "on",
        "Editor$Edit$Advanced$chkDisplayHomePage": "on",
        "Editor$Edit$Advanced$chkComments": "on",
        "Editor$Edit$Advanced$chkMainSyndication": "on",
        "Editor$Edit$lkbDraft": "存为草稿",
        }
    r2 = s.post(url2, data=http://www.mamicode.com/body, verify=False)
    print r2.url
    return r2.url

def get_postid(u):
    ‘‘‘正则提取postid‘‘‘
    import re
    postid = re.findall(r"postid=(.+?)&", u)
    print postid  # 这里是list
    if len(postid) < 1:
        return ‘‘
    else:
        return postid[0]

def delete_box(s,url3, postid):
    ‘‘‘删除草稿箱‘‘‘
    json3 = {"postId": postid}
    r3 = s.post(url3, json=json3, verify=False)
    print r3.json()

if __name__ == "__main__":
    url = "https://passport.cnblogs.com/user/signin"
    payload = {
                "input1": "xxx",
                "input2": "xxx",
                "remember": True
               }
    s = requests.session()
    login(s, url, payload,)
    url2 = "https://i.cnblogs.com/EditPosts.aspx?opt=1"
    u = save_box(s, url2, "标题", "正文内容")
    postid = get_postid(u)
    url3 = "https://i.cnblogs.com/post/delete"
    delete_box(s, url3, postid)
对python接口自动化有兴趣的,可以加python接口自动化QQ群:226296743

也可以关注下我的个人公众号:

技术分享

python接口自动化8-参数化