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

Python Selenium中如何通过aria-label内数值定位HTML交互元素

Selenium通过aria-label属性精准定位元素方案

目标元素结构

需要交互的加入购物车按钮HTML代码如下:

<span class="a-button-inner">
    <input name="submit.addToCart" aria-label="Aggiungi al carrello dal venditore VERONCART SRL con prezzo 775,00&nbsp;€
" aria-labelledby="" class="a-button-input" type="submit">
<span id="a-autoid-2-offer-1-announce" class="a-button-text" aria-hidden="true"> Aggiungi al carrello </span>
</span>

原有定位写法失效原因

之前尝试的两种写法均存在语法和匹配逻辑错误,无法命中元素:

  • XPath写法错误:contains函数语法不符合规范,且匹配目标是元素文本节点,但775存储在input标签的aria-label属性中,不属于元素直接文本,匹配逻辑完全不成立。
  • CSS选择器写法错误:误用了XPath的//前缀作为CSS选择器开头,且错误匹配value属性,目标数值并不存在于value属性中,自然定位失败。

可用正确定位代码

核心匹配逻辑:筛选提交类型的input标签,判断其aria-label属性是否包含目标数值775即可,支持XPath和CSS选择器两种写法:

XPath写法

Selenium 4.0+ 推荐写法:

from selenium.webdriver.common.by import By
# 定位aria-label包含775的提交按钮
target_btn = wd.find_element(By.XPATH, '//input[@type="submit" and contains(@aria-label, "775")]')

旧版本兼容写法:

target_btn = wd.find_element_by_xpath('//input[@type="submit" and contains(@aria-label, "775")]')

CSS选择器写法

Selenium 4.0+ 推荐写法:

from selenium.webdriver.common.by import By
# CSS选择器中*=代表属性包含指定字符串的匹配规则
target_btn = wd.find_element(By.CSS_SELECTOR, 'input[type="submit"][aria-label*="775"]')

旧版本兼容写法:

target_btn = wd.find_element_by_css_selector('input[type="submit"][aria-label*="775"]')

补充注意事项

如果页面存在动态加载、元素渲染延迟的情况,不要直接调用find_element方法,搭配显式等待判断元素可点击后再执行交互,可大幅降低定位失败的概率。

内容的提问来源于stack exchange,提问作者Antonio Calo'

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 08:31:09