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

Selenium ChromeDriver如何定位无id/name属性的同类型按钮元素

元素定位解决方案

以下是几种适配不同场景的稳定定位方案,Selenium、Playwright等主流自动化测试框架均可直接使用:

  • 方案1:XPath结合文本精准定位(稳定性最高)
    直接匹配按钮的文本内容,不受按钮排序、页面结构微调影响,适合按钮文本固定的场景,各按钮的定位写法如下:
    • Week按钮://div[contains(@class, "mv-button-base") and text()="Week"]
    • Month按钮://div[contains(@class, "mv-button-base") and text()="Month"]
    • Quarter按钮://div[contains(@class, "mv-button-base") and text()="Quarter"]
    • Season按钮://div[contains(@class, "mv-button-base") and text()="Season"]
    • Year按钮://div[contains(@class, "mv-button-base") and text()="Year"]
      如果要直接定位当前选中的按钮,可使用://div[contains(@class, "mv-item-selected")]
  • 方案2:CSS选择器结合索引定位
    适合按钮排序固定不会变动的场景,通过父容器+子元素序号匹配:
    • Week按钮:.mv-button-group > div:nth-child(1)
    • Month按钮:.mv-button-group > div:nth-child(2)
    • Quarter按钮:.mv-button-group > div:nth-child(3)
    • Season按钮:.mv-button-group > div:nth-child(4)
    • Year按钮:.mv-button-group > div:nth-child(5)
  • 方案3:批量获取后过滤
    先获取所有同类型按钮的列表,再按索引或者文本筛选,以Selenium Python写法为例:
    from selenium.webdriver.common.by import By
    # 获取全部5个按钮
    button_list = driver.find_elements(By.CLASS_NAME, "mv-hyperlink-button")
    # 按索引取:0对应Week,1对应Month,以此类推
    week_button = button_list[0]
    # 按文本过滤的通用写法
    def get_button(text):
        for btn in button_list:
            if btn.text.strip() == text:
                return btn
    month_button = get_button("Month")
    

内容的提问来源于stack exchange,提问作者Leo_Liu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:00:00