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

Python/Selenium实现:定位无序列表中指定金额元素并点击对应购买按钮,disabled状态下循环重试

Solution for Targeted Purchase Button Click with Wait Logic

Let's walk through how to build this logic so you can click the exact purchase button matching your target price, and wait if it's disabled. Here's a straightforward, robust implementation:

Step-by-Step Code Implementation

First, we'll use a loop to repeatedly check the button's state, and only click it once it's no longer disabled. We'll also make sure we're targeting the exact button paired with your price (so we don't accidentally click one of the other 100 buttons):

from selenium import webdriver
import time

# Initialize the browser (raw string avoids escape character issues in file path)
PATH = r"C:\Users\abc\Desktop\Automation\chromedriver.exe"
driver = webdriver.Chrome(PATH)

# Define your target price here (easy to modify later)
target_price = "$30.00"
max_wait_time = 60  # Optional: Set a timeout to avoid infinite loops
start_time = time.time()

while time.time() - start_time < max_wait_time:
    try:
        # First, locate the span containing your target price
        price_span = driver.find_element_by_xpath(f"//span[text()='{target_price}']")
        
        # Navigate up to the shared parent container, then grab the corresponding purchase button
        # This ensures we're getting the button linked to YOUR target price, not another one
        purchase_button = price_span.find_element_by_xpath("../../div[@class='Market-item Buy']/a")
        
        # Check if the button is disabled by looking at its class attribute
        button_classes = purchase_button.get_attribute("class")
        if "disabled" not in button_classes:
            purchase_button.click()
            print(f"✅ Successfully clicked purchase button for {target_price}!")
            break
        else:
            print(f"⏳ Purchase button for {target_price} is disabled, waiting 1 second...")
            time.sleep(1)
    
    # Handle cases where elements might be stale or not found temporarily
    except Exception as e:
        print(f"⚠️ Encountered an issue: {str(e)}. Retrying in 1 second...")
        time.sleep(1)
else:
    # If we exit the loop without breaking, we hit the timeout
    print(f"❌ Timed out after {max_wait_time} seconds waiting for the button to enable.")

Key Details Explained

  • Targeting the Correct Button: The XPath ../../div[@class='Market-item Buy']/a moves up two levels from the price span (to the shared List-rowContent Market container) then finds the purchase button in that same row. This guarantees we're interacting with the button paired with your target price.
  • Avoiding Infinite Loops: The max_wait_time variable lets you set a limit on how long the script will wait, so it doesn't run forever if the button never enables.
  • Handling Stale Elements: Wrapping the logic in a try/except block catches errors like StaleElementReferenceException (which happens if the page refreshes or elements reload) and retries the check.
  • Raw String for Path: Using r"PATH" avoids issues with escape characters in your ChromeDriver file path.

Example Behavior

  • If your target price is $30.00: The script will immediately find the enabled button and click it.
  • If your target price is $50.00: The script will loop, printing a waiting message every second until the button's disabled class is removed, then click it (or time out if you set a limit).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 11:49:11