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

如何用Selenium点击无类名、ID或链接文本的a标签?附ogimet实操场景

Hey Javier, let's tackle your two Selenium click questions step by step:

1. Clicking the Target <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()

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()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:32:54