python接口自動化測試十四: 用正則表達式提取數據
import requests
import re
url = 'xxxx'
r = requests.post(url)
# 正則公式:
postid = re.findall(r"(.+?)", r.url) # r.url:匹配的url對象
# ^表示從頭開始匹配
u = re.findall(r"^(.+?)\?", url)
# 如果參數在末尾,匹配到最后
# 參數:postid=35454&actiontip=按時發
res = re.findall(r"actiontip=(.+?)$", r.url)
# 知道字符串前、后,取中間,這里的前、后所代表的值須為固定不變的
postid = re.findall(r"前(.+?)后", r.url)
# 參數:postid=35454&actiontip=按時發
# 取:35454 前“postid=” 后“&”
postid = re.findall(r"postid=(.+?)&", r.url)
print(postid) # 這里是list
print(postid[0]) # 提取為字符串
# 參數關聯
url1 = 'xxxxx'
body = {'postid': postid}
r1 = requests.post(url, json=body)
# 判斷請求是否成功
if r1.json()['xx']:
print('成功')
else:
print('失敗')
'''
# 正則提取需要的參數值
import re
postid = re.findall(r"postid=(.+?)&", r2.url)
print postid
# 這里是list
# 提取為字符串
print postid[0]
1.先導入re模塊
2.re.findall(匹配規則,查找對象)是查找所有符合規則的
3. postid=(.+?)& 這個意思是查找postid=開頭,&結尾的,返回字符串中間內容,如:postid=12345&a=111
那就返回[‘12345’]
4.返回的結果是list
5.list[0]是取下標第一個
'''