You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium金额变动验证:余额1加1后变为2的实现方法

Selenium实现金额变动验证方案(初始余额1→操作后余额2)

Alright, let's walk through how to implement this balance verification with Selenium step by step. I'll break it down into straightforward logic, actionable steps, a working code example, and key pitfalls to avoid.

核心思路

The core logic is simple: capture the initial balance value, trigger the "+1" action, wait for the balance to update, then verify the new balance equals the initial value plus 1. No fancy tricks here—just reliable, sequential checks.

具体实现步骤

  • 初始化驱动与打开页面: Launch your preferred browser driver (Chrome, Firefox, etc.) and navigate to the target page where the balance and "+1" button live.
  • 获取初始余额: Locate the element displaying the balance, extract its text content, and convert it to a numeric type (int/float) so we can do math with it.
  • 触发+1操作: Find and click the button/element that triggers the "+1" balance update.
  • 等待余额更新: Use explicit waits (critical here!) to ensure the balance element has finished updating—this avoids race conditions with page loads or AJAX requests.
  • 获取更新后余额: Extract the new balance value and convert it to a numeric type as well.
  • 执行验证: Assert that the new balance exactly equals initial_balance + 1.
  • 清理资源: Close the browser driver to free up system resources, even if something goes wrong.

代码示例(Python)

Here's a complete, runnable Python example using Selenium. Make sure to adjust the element locators to match your actual page's HTML structure:

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

# Initialize Chrome driver (use webdriver-manager if you don't want to manage driver paths manually)
driver = webdriver.Chrome()
driver.get("https://your-target-page-url.com")

try:
    # 1. Get initial balance (wait for element to load first)
    balance_locator = (By.ID, "balance")  # Replace with your actual element locator (XPath/CSS work too)
    initial_balance_element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located(balance_locator)
    )
    initial_balance = float(initial_balance_element.text)
    print(f"Initial balance: {initial_balance}")

    # 2. Trigger the +1 action (wait for button to be clickable)
    add_btn_locator = (By.ID, "add-one-btn")  # Replace with your actual button locator
    add_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable(add_btn_locator)
    )
    add_button.click()

    # 3. Wait for balance to update to expected value
    expected_balance = initial_balance + 1
    WebDriverWait(driver, 10).until(
        EC.text_to_be_present_in_element(balance_locator, str(expected_balance))
    )

    # 4. Get updated balance and verify
    new_balance = float(driver.find_element(*balance_locator).text)
    print(f"Updated balance: {new_balance}")

    assert new_balance == expected_balance, f"Verification failed! Expected {expected_balance}, got {new_balance}"
    print("Balance update verified successfully!")

finally:
    # Ensure driver is closed even if an error occurs
    driver.quit()

关键注意事项

  • Element Locators: Stick to reliable locators like unique IDs, specific CSS selectors, or stable XPaths. Avoid fragile locators like generic class names that might change with page updates.
  • Explicit Waits: Never use time.sleep()—it's slow and brittle. Selenium's WebDriverWait with expected conditions ensures you only proceed when the page is ready.
  • Data Type Conversion: Balance values on the page are strings, so convert them to int or float before comparisons. This prevents weird edge cases (like decimal balances failing string checks).
  • Error Handling: The try-finally block guarantees the driver closes even if an assertion fails or an exception is thrown—no hanging browser windows left behind.
  • Async Operations: If the "+1" action uses AJAX or background API calls, you might need to wait for loading spinners to disappear or network requests to complete before checking the balance.

内容的提问来源于stack exchange,提问作者Giorgi Tediashvili

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:30:35