python 正则表达式之接口自动化

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

示例代码

1. 提取HTML中的链接

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

 
  1. import re

  2. html = 'Example Visit Test Site'

  3. pattern = re.compile(r'href="(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)"')

  4. matches = pattern.findall(html)

  5. print(matches)

  6. # 输出结果: ['https://www.example.com', 'http://test.example.org']

'

运行

运行

2. 验证邮箱格式

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

 
  1. email = "example@example.com"

  2. pattern = re.compile(r'^[\w\.-]+@[\w\.-]+\.\w+$')

  3. if pattern.match(email):

  4. print("Valid email")

  5. else:

  6. print("Invalid email")

  7. # 输出结果: Valid email

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

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

 
  1. json_text = '{"name": "John Doe", "age": 30, "city": "New York"}'

  2. pattern = re.compile(r'"age": (\d+)')

  3. match = pattern.search(json_text)

  4. if match:

  5. age = match.group(1)

  6. print(f"Age: {age}")

  7. else:

  8. print("Age not found")

  9. # 输出结果: Age: 30

4. 匹配电话号码

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

 
  1. text = "Contact us at +1 (123) 456-7890 or +44-20-7123-4567."

  2. pattern = re.compile(r'\+?\d{1,3}[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}')

  3. phone_numbers = pattern.findall(text)

  4. print(phone_numbers)

  5. # 输出结果: ['+1 (123) 456-7890', '+44-20-7123-4567']

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

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

 
  1. message = "Your order has been processed successfully."

  2. sensitive_words = ["error", "failed"]

  3. pattern = re.compile("|".join(map(re.escape, sensitive_words)))

  4. if pattern.search(message):

  5. print("Message contains sensitive words.")

  6. else:

  7. print("Message is clean.")

  8. # 输出结果: Message is clean.

6. 提取HTTP状态码

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

 
  1. log_entry = "GET /api/data HTTP/1.1 200 OK"

  2. pattern = re.compile(r'\b\d{3}\b')

  3. status_code = pattern.search(log_entry)

  4. if status_code:

  5. print(f"Status Code: {status_code.group()}")

  6. else:

  7. print("No status code found.")

  8. # 输出结果: Status Code: 200

7. 验证日期格式

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

 
  1. date_str = "2023-04-01"

  2. pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')

  3. if pattern.match(date_str):

  4. print("Valid date format")

  5. else:

  6. print("Invalid date format")

  7. # 输出结果: Valid date format

8. 提取URL参数

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

 
  1. url = "https://www.example.com/search?q=python+regex&lang=en"

  2. pattern = re.compile(r'q=(.*?)(&|$)')

  3. match = pattern.search(url)

  4. if match:

  5. query = match.group(1)

  6. print(f"Search Query: {query}")

  7. else:

  8. print("Query parameter not found")

  9. # 输出结果: Search Query: python+regex

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

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

 
  1. password = "P@ssw0rd"

  2. pattern = re.compile(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$')

  3. if pattern.match(password):

  4. print("Strong password")

  5. else:

  6. print("Weak password")

  7. # 输出结果: Strong password

10. 提取XML标签内容

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

 
  1. xml_data = 'Some description here.'

  2. pattern = re.compile(r'')

  3. title = pattern.search(xml_data).group(1)

  4. print(title)

  5. # 输出结果: Sample Title

感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

 

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!有需要的小伙伴可以点击下方小卡片领取   

 

  • 14
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值