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]是取下标第一个
'''
 

猜你喜欢

转载自www.cnblogs.com/zhongyehai/p/9159840.html