Python 正则表达式之接口自动化!

正则表达式(Regular Expression)在接口自动化测试中非常有用,可以用来从响应数据中提取特定的信息、验证返回内容是否符合预期格式等。

示例代码

1. 提取HTML中的链接

场景: 从一段HTML文本中提取所有的URL链接。

import rehtml = 'Example Visit Test Site'pattern = re.compile(r'href="(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)"')matches = pattern.findall(html)print(matches)# 输出结果: ['https://www.example.com', 'http://test.example.org']

2. 验证邮箱格式

场景: 验证一个字符串是否符合邮箱地址的基本格式。

email = "example@example.com"pattern = re.compile(r'^[\w\.-]+@[\w\.-]+\.\w+$')if pattern.match(email):    print("Valid email")else:    print("Invalid email")# 输出结果: Valid email

3. 提取JSON响应中的特定字段

场景: 从JSON格式的文本中提取某个键的值。

json_text = '{"name": "John Doe", "age": 30, "city": "New York"}'pattern = re.compile(r'"age": (\d+)')match = pattern.search(json_text)if match:    age = match.group(1)    print(f"Age: {age}")else:    print("Age not found")# 输出结果: Age: 30

4. 匹配电话号码

场景: 验证并提取字符串中的电话号码。

text = "Contact us at +1 (123) 456-7890 or +44-20-7123-4567."pattern = re.compile(r'\+?\d{1,3}[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}')phone_numbers = pattern.findall(text)print(phone_numbers)# 输出结果: ['+1 (123) 456-7890', '+44-20-7123-4567']

5. 检查字符串中是否包含敏感词

场景: 确认API返回的消息中不包含任何敏感词汇。​​​​​​​

message = "Your order has been processed successfully."sensitive_words = ["error", "failed"]pattern = re.compile("|".join(map(re.escape, sensitive_words)))if pattern.search(message):    print("Message contains sensitive words.")else:    print("Message is clean.")# 输出结果: Message is clean.

6. 提取HTTP状态码

场景: 从日志中提取HTTP请求的状态码。​​​​​​​

log_entry = "GET /api/data HTTP/1.1 200 OK"pattern = re.compile(r'\b\d{3}\b')status_code = pattern.search(log_entry)if status_code:    print(f"Status Code: {status_code.group()}")else:    print("No status code found.")# 输出结果: Status Code: 200

7. 验证日期格式

场景: 确保日期字符串遵循YYYY-MM-DD格式。​​​​​​​

date_str = "2023-04-01"pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')if pattern.match(date_str):    print("Valid date format")else:    print("Invalid date format")# 输出结果: Valid date format

8. 提取URL参数

场景: 从URL中提取查询参数的值。​​​​​​​

url = "https://www.example.com/search?q=python+regex&lang=en"pattern = re.compile(r'q=(.*?)(&|$)')match = pattern.search(url)if match:    query = match.group(1)    print(f"Search Query: {query}")else:    print("Query parameter not found")# 输出结果: Search Query: python+regex

9. 校验密码强度(至少包含一个大写字母、一个小写字母、一个数字和特殊字符)

场景: 验证用户输入的密码是否符合复杂度要求。​​​​​​​

password = "P@ssw0rd"pattern = re.compile(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$')if pattern.match(password):    print("Strong password")else:    print("Weak password")# 输出结果: Strong password

10. 提取XML标签内容

场景: 从XML数据中提取特定标签的内容。​​​​​​​

xml_data = 'Some description here.'pattern = re.compile(r'')title = pattern.search(xml_data).group(1)print(title)# 输出结果: Sample Title

最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 

软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值