Selenium Python:如何点击名为Boleto Bancario的第二个选项?
Hey there! Let's break down how to target and click that second "Boleto Bancario" option using Selenium in Python. The approach depends a bit on your page's HTML structure, but here are the most common and reliable methods:
1. Locate All Matching Elements & Select the Second One
If your options are part of a list (like <li> items) or scattered across the page, first grab all elements with the text "Boleto Bancario", then pick the second one (remember Python uses 0-based indexing, so we'll use index 1):
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 your driver (Chrome example) driver = webdriver.Chrome() driver.get("your_target_page_url") # Wait for at least 2 matching elements to load (avoids race conditions) wait = WebDriverWait(driver, 10) boleto_options = wait.until( EC.presence_of_all_elements_located((By.XPATH, "//*[text()='Boleto Bancario']")) ) # Click the second option if it exists if len(boleto_options) >= 2: boleto_options[1].click() else: print("Couldn't find at least two 'Boleto Bancario' options on the page")
2. Directly Target the Second Element with XPath
You can also use XPath's position selector to directly grab the second matching element in one go:
# Wait for the second element to be clickable second_boleto = wait.until( EC.element_to_be_clickable((By.XPATH, "(//*[text()='Boleto Bancario'])[2]")) ) second_boleto.click()
3. If It's a Dropdown (<select> Element)
If the options are inside a <select> dropdown, use Selenium's Select class to handle it properly. Note that select_by_visible_text() picks the first match, so we'll loop through options to find the second one:
from selenium.webdriver.support.ui import Select # Locate the dropdown element (adjust the locator to match your page) dropdown = Select(driver.find_element(By.ID, "payment_method_dropdown")) # Loop through options to find the second "Boleto Bancario" for index, option in enumerate(dropdown.options): if option.text.strip() == "Boleto Bancario" and index == 1: dropdown.select_by_index(index) break else: print("Second 'Boleto Bancario' option not found in the dropdown")
Pro Tips:
- Always use explicit waits (like
WebDriverWait) instead oftime.sleep()—it makes your code more reliable and faster. - If the text has extra spaces or accents, use
normalize-space()in XPath://*[normalize-space(text())='Boleto Bancario']to match correctly. - If the element is hidden or overlapped, you might need to use
execute_scriptto click it:driver.execute_script("arguments[0].click();", second_boleto)
内容的提问来源于stack exchange,提问作者NickWaterBr

