Requests方法 -- 参数化

Posted teachertao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Requests方法 -- 参数化相关的知识,希望对你有一定的参考价值。

import requests
#禁用安全请求警告
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
"""
1.由于登录时候是多加 2 个 cookie,我们可以先用 get 方法打开登录首页,获取部分 cookie
2.再把登录需要的 cookie 添加到 session 里
3.添加成功后,随便编辑正文和标题保存到草稿箱
"""

def Blog_login(url,s):
# 先打开登录首页,获取部分 cookie
header =
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/73.0.3683.103 Safari/537.36"


# s = requests.Session()
r = s.get(url,headers=header)
print(r.cookies)

# 添加登录需要的两个 cookie
c = requests.cookies.RequestsCookieJar()
c.set(".Cnblogs.AspNetCore.Cookies","自己抓取的cookie")
c.set(".CNBlogsCookie","自己抓取的cookie")
# c.set(‘AlwaysCreateItemsAsActive‘,"True")
# c.set(‘AdminCookieAlwaysExpandAdvanced‘,"True")
s.cookies.update(c)
print(s.cookies)
# return s.cookies

def save_box(s,url2,title,body_data):
# 登录成功后保存编辑内容
# r1 = s.get("https://i.cnblogs.com/EditPosts.aspx?opt=1", headers=Blog_login(s),verify=False)
# print(r1.text)

# 保存草稿箱
body =
"__VIEWSTATE":"",
"__VIEWSTATEGENERATOR":"FE27D343",
"Editor$Edit$txbTitle":title,
"Editor$Edit$EditorBody":body_data,
"Editor$Edit$Advanced$ckbPublished":"on",
"Editor$Edit$Advanced$chkDisplayHomePage":"on",
"Editor$Edit$Advanced$chkComments":"on",
"Editor$Edit$Advanced$chkMainSyndication":"on",
"Editor$Edit$Advanced$txbEntryName":"",
"Editor$Edit$Advanced$txbExcerpt":"",
"Editor$Edit$Advanced$txbTag":"",
"Editor$Edit$Advanced$tbEnryPassword":"",
"Editor$Edit$lkbDraft":"存为草稿",


r2 = s.post(url2,data=body,verify=False)
# print(r.content.decode("utf-8"))
#获取当前的url地址
save_url = r2.url
print(save_url)
return save_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):
#删除草稿箱
form_json = "postId":postid
result = s.post(url3,json=form_json,verify=False)
print(result.json())

if __name__ == ‘__main__‘:
url = "https://account.cnblogs.com/signin?returnurl=https%3A%2F%2Fwww.cnblogs.com%2F"
s = requests.Session()
Blog_login(url,s)
url2 = "https://i.cnblogs.com/EditPosts.aspx?opt=1"
u = save_box(s,url2,"Hi,你们","Are you ok?")
postid = get_postid(u)
url3 = "https://i.cnblogs.com/post/delete"
delete_box(s,url3,postid)


以上是关于Requests方法 -- 参数化的主要内容,如果未能解决你的问题,请参考以下文章

requests接口自动化-数据库参数化

requests接口自动化-excel参数化

python+requests接口自动化测试4--参数化

单元测试参数化

python接口自动化--封装和参数化及unittest用例

locust参数化