如何用Selenium点击无类名、ID或链接文本的a标签?附ogimet实操场景
Hey Javier, let's tackle your two Selenium click questions step by step:
<a> Tag (Avoiding XPath) Your target link has a clear, unique href attribute, which is perfect for reliable targeting without XPath. Here are a couple of solid options:
Option 1: Target by href using CSS Selector
This is the most stable approach since the href value is unlikely to change unexpectedly:
from selenium.webdriver.common.by import By # Locate the link and click it target_link = driver.find_element(By.CSS_SELECTOR, 'a[href="/sondc.phtml"]') target_link.click()
Option 2: Target by Partial Link Text
If the visible text "Sondeos por territorios" is unique on the page, you can use partial link text to skip the bolded leading "S":
from selenium.webdriver.common.by import By target_link = driver.find_element(By.PARTIAL_LINK_TEXT, "Sondeos por territorios") target_link.click()
If the full visible text ("SSondeos por territorios") is unique, you could also use By.LINK_TEXT with the complete string instead.
When an <a> tag has no obvious identifiers, you'll need to leverage its context or hidden attributes. Here are practical methods:
Use Parent/Child Hierarchy with CSS Selectors
If the link lives inside a container with a known ID/class, target it via the parent's context:
from selenium.webdriver.common.by import By # Example: Link is the 2nd <a> inside a div with id="main-menu" target_link = driver.find_element(By.CSS_SELECTOR, '#main-menu a:nth-child(2)') target_link.click()
Target via Child Elements Inside the Link
If the <a> contains other elements (like an image or span), use those elements' attributes to locate the parent link:
from selenium.webdriver.common.by import By # Example: Link contains an image with alt text "download-icon" (requires Selenium 4.0+) target_link = driver.find_element(By.CSS_SELECTOR, 'a:has(img[alt="download-icon"])') target_link.click()
Use Relative Locators
If you can identify a nearby element (e.g., a button or label), use relative positioning to find the link:
from selenium.webdriver.common.by import By from selenium.webdriver.support.relative_locator import with_tag_name # First locate a known adjacent element reference_btn = driver.find_element(By.ID, "submit-form") # Find the <a> tag to the right of the reference button target_link = driver.find_element(with_tag_name('a').to_right_of(reference_btn)) target_link.click()
Target Hidden Attributes
Many links have hidden custom attributes (like data-* or title). Use these if available:
from selenium.webdriver.common.by import By # Example: Link has a custom data-action attribute target_link = driver.find_element(By.CSS_SELECTOR, 'a[data-action="delete-item"]') target_link.click()
内容的提问来源于stack exchange,提问作者Javier

