python接口自動化測試十四: 用正則表達式提取數據


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]是取下標第一個
'''

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM