如何用Selenium和Python点击页面中第二个重复的HTML元素
Let's break down the issues with your current code and fix them step by step:
First, the core problem with your button targeting
Your line driver.find_element_by_link_text("SHOP NOW")[a] won't work because find_element_by_link_text() returns only the first matching element, not a list. To get all "SHOP NOW" buttons, you need to use find_elements_by_link_text() (note the plural "elements") which returns a list of all matching elements.
Step 1: Get all valid "SHOP NOW" buttons
First, fetch all the buttons, then filter out the disabled ones (the grayed-out ones from low stock). We can check if a button is enabled by:
- Looking for a disabled class (common for styled disabled buttons, e.g.,
button-disabled– you may need to inspect the grayed button's HTML to confirm the exact class) - Checking if the element has a
disabledattribute - Using Selenium's
is_enabled()method (though sometimes styled disabled buttons might still returnTruehere, so combining with class checks is safer)
Step 2: Target the second enabled button
Once we have the list of enabled buttons, we can check if there's at least a second one (index 1, since Python lists are 0-indexed) and click it.
Revised Code
Here's the adjusted version of your mainclick function with these fixes:
import time from selenium import webdriver def mainclick(website): while True: time.sleep(1) # Get all "SHOP NOW" buttons using precise CSS selector matching your button's classes shop_now_buttons = driver.find_elements_by_css_selector('a.button-called-out.button-full.facetedResults-cta') # Filter out disabled buttons (adjust the class check based on your site's actual disabled button HTML) enabled_buttons = [btn for btn in shop_now_buttons if 'button-disabled' not in btn.get_attribute('class') and btn.is_enabled()] # Check if there's at least a second enabled button to click if len(enabled_buttons) >= 2: try: # Click the SECOND enabled button (index 1, since lists are 0-indexed) enabled_buttons[1].click() time.sleep(3) # Try adding to cart if possible try: add_to_cart_btn = driver.find_element_by_id("addToCartButtonTop") if add_to_cart_btn.is_enabled(): add_to_cart_btn.click() except Exception as e: print(f"Add to cart failed: {str(e)}") finally: # Ensure we return to the results page regardless driver.execute_script("window.history.go(-1)") except Exception as e: print(f"Couldn't click button: {str(e)}") else: print("Not enough enabled SHOP NOW buttons on this page") # Navigate to next page, exit loop if no next page exists try: driver.find_element_by_link_text("Next Page").click() except Exception as e: print("No more pages left, exiting loop") break # Initialize driver and run the function driver = webdriver.Chrome() # Adjust to your driver type mainweb = "https://www.lenovo.com/us/en/outletus/laptops/c/LAPTOPS?q=%3Aprice-asc%3AfacetSys-Memory%3A16+GB%3AfacetSys-Processor%3AIntel%C2%AE+Core%E2%84%A2+i7%3AfacetSys-Processor%3AIntel%C2%AE+Core%E2%84%A2+i5%3AfacetSys-Memory%3A8+GB&uq=&text=#" driver.get(mainweb) mainclick(mainweb)
Key Improvements Explained
- Precise button targeting: Using
find_elements_by_css_selectorinstead of link text ensures we only grab buttons with your exact target classes, avoiding accidental matches with other "SHOP NOW" text on the page. - Disabled button filtering: The list comprehension checks for a disabled-specific class (replace
button-disabledwith the actual class from your grayed-out button's HTML) and verifies the button's interactivity withis_enabled(). - Safe index access: We check if
enabled_buttonshas at least 2 elements before attempting to click index 1, preventing index-out-of-range errors. - Robust error handling: Restructured try/except blocks make it clearer where failures might happen, and the
finallyblock ensures we always return to the results page.
Notes for Your Specific Site
- Inspect the grayed-out "SHOP NOW" button's HTML to find the exact disabled class (e.g., maybe
is-disabledorbutton-inactive), then update the filter condition accordingly. - If
is_enabled()doesn't work for your styled buttons, you can also check if the button'shrefis a valid product link (disabled buttons often havehref="#"or no href attribute).
内容的提问来源于stack exchange,提问作者Bob Stone

