如何用 Python 在 Selenium 中测试邮件验证

· 5 分钟阅读 · QuickInbox 团队

  • Selenium
  • Python
  • 邮件测试

Selenium 能填写你的注册表单,但大多数测试套件会停在“请查看你的邮箱”。有了一次性邮箱 API,你的 Python 测试就能读取邮件并完成任务。

第 1 步:邮箱辅助函数

这里使用 QuickInbox 的免费 API,无需注册或密钥。安装 requests 并添加:

# inbox.py - disposable inboxes from QuickInbox's free API (no key needed)
import re, time, requests

BASE = "https://quickinbox.net"

def create_inbox(minutes=10):
    r = requests.post(f"{BASE}/api/generate", json={"minutes": minutes})
    r.raise_for_status()
    address = r.json()["address"]
    return address, address.split("@")[0]

def wait_for_email(local, subject="", timeout=60, interval=2):
    deadline = time.time() + timeout
    while time.time() < deadline:
        r = requests.get(f"{BASE}/api/inbox/{local}")
        if r.ok:
            for m in r.json().get("messages", []):
                if subject in m["subject"]:
                    return m  # id, from, subject, text, html, receivedAt
        time.sleep(interval)
    raise TimeoutError(f"No email with subject {subject!r} in {timeout}s")

def extract_code(email):
    m = re.search(r"\b(\d{4,8})\b", email.get("text") or "")
    if not m:
        raise ValueError("No code found")
    return m.group(1)

def extract_link(email, pattern):
    for url in re.findall(r'href="([^"]+)"', email.get("html") or ""):
        url = url.replace("&amp;", "&")
        if re.search(pattern, url):
            return url
    raise ValueError(f"No link matching {pattern}")

第 2 步:测试验证链接

# test_signup.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import inbox

def test_signup_and_verify():
    address, local = inbox.create_inbox()
    driver = webdriver.Chrome()
    try:
        driver.get("https://staging.example.com/signup")
        driver.find_element(By.NAME, "email").send_keys(address)
        driver.find_element(By.NAME, "password").send_keys("Correct-Horse-42")
        driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()

        email = inbox.wait_for_email(local, subject="Verify")
        driver.get(inbox.extract_link(email, r"/verify"))

        WebDriverWait(driver, 10).until(
            EC.text_to_be_present_in_element((By.TAG_NAME, "body"), "verified"))
    finally:
        driver.quit()

第 3 步:或者测试一次性验证码

email = inbox.wait_for_email(local, subject="code")
driver.find_element(By.NAME, "code").send_keys(inbox.extract_code(email))

小技巧

  • 给每个测试一个单独的邮箱,这样测试就能用 pytest-xdist 并行运行。
  • 免费 API 每个 IP 每分钟大约能创建 10 个新地址。大型并行测试套件请用 Business API,命名空间下的任何标签都是一个新地址,无需创建调用。
  • 绝不要把真实数据发到免费邮箱:知道地址的任何人都能读取。
  • 短信验证码也是同样思路:Selenium 中的短信 2FA。

相关指南

现在就试:上面的免费接口无需注册,文档在临时邮箱 API 页面。如需私有邮箱、webhook 和大规模 CI,QuickInbox Business API 提供每月 5,000 封邮件的免费套餐。

← 全部文章