
本文介绍在 Selenium 自动化测试中,当目标元素无 ID、class 或 name 等显式定位器时,如何通过 XPath/CSS 选择器定位含混合文本的 HTML 元素,并利用正则表达式(re.findall(r'\d+', text))高效提取其中的连续数字。
本文介绍在 selenium 自动化测试中,当目标元素无 id、class 或 name 等显式定位器时,如何通过 xpath/css 选择器定位含混合文本的 html 元素,并利用正则表达式(`re.findall(r'\d+', text)`)高效提取其中的连续数字。
在实际 Web 自动化场景中,常遇到类似
此时应分两步解决:精准定位 + 文本清洗提取。
✅ 第一步:灵活定位目标元素
由于示例中
from selenium import webdriver
from selenium.webdriver.common.by import By
import re
driver = webdriver.Chrome()
driver.get("https://example.com") # 替换为目标网页URL
# 方案1:通过 td 标签内文模糊匹配(推荐,鲁棒性强)
td_element = driver.find_element(By.XPATH, "//td[contains(text(), 'FB-')]")
text_content = td_element.text # → "FB-91927"
# 方案2:通过 li.title 定位(题目中已知 class)
li_element = driver.find_element(By.CSS_SELECTOR, "li.title")
text_content = li_element.text # → "FB-91927 is your Facebook confirmation code"
⚠️ 注意:find_elements_by_class_name("title") 已被 Selenium 4+ 弃用,必须改用 By.CLASS_NAME 或 By.CSS_SELECTOR 配合 find_element()(单元素)或 find_elements()(多元素)。
✅ 第二步:用正则提取纯数字
获取原始文本后,使用 re.findall(r'\d+', text) 提取所有连续数字片段(\d+ 表示一个或多个数字):
# 提取所有数字组(返回字符串列表)
numbers = re.findall(r'\d+', text_content)
print(numbers) # 输出:['91927'](若文本为 "FB-91927" 或 "FB-91927 is your code")
# 获取第一个数字(通常即所需验证码)
confirmation_code = numbers[0] if numbers else None
print("Extracted code:", confirmation_code) # → "91927"
如需更严格匹配(例如仅提取 5 位数字),可升级正则:
# 仅匹配恰好5位数字
code_5digits = re.search(r'\b\d{5}\b', text_content)
if code_5digits:
confirmation_code = code_5digits.group() # → "91927"
✅ 完整可运行示例
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import re
options = Options()
options.add_argument("--headless") # 无界面模式
driver = webdriver.Chrome(options=options)
try:
driver.get("https://your-target-page.com")
# 定位含 FB- 前缀的 li 元素(兼容 class="title" 场景)
element = driver.find_element(By.XPATH, "//li[contains(@class,'title') or contains(text(),'FB-')]")
raw_text = element.text
# 提取数字
digits = re.findall(r'\d+', raw_text)
code = digits[0] if digits else ""
print(f"✅ Extracted numeric code: {code}")
finally:
driver.quit()
? 关键总结:
- 避免依赖不稳定属性,善用 contains(text(), ...) 或 contains(@class, ...) 的 XPath;
- 正则 r'\d+' 是提取数字的通用解法,按需可扩展为 \d{4,6}、\b\d{5}\b 等精确模式;
- 始终添加异常处理(如 NoSuchElementException)和空值校验,保障脚本健壮性。











