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

Python Selenium中点击按钮时‘invalid locator’问题的解决方法

解决Selenium中InvalidArgumentException: invalid locator错误

你的问题出在定位器的参数格式上,Selenium的find_element方法第一个参数不能直接传字符串"xPath",必须使用By类里的常量。

修正后的代码

首先要导入By类,然后修改定位器参数:

from selenium.webdriver.common.by import By

Execute_Button = driver.find_element(By.XPATH, '//button[text()="Execute "]')

额外排查点

  • 确认按钮文本确实带有末尾空格,如果实际按钮文本是"Execute"(无空格),需要把XPath里的"Execute "改成"Execute"
  • 如果还是定位失败,可以换用更稳定的定位方式,比如通过按钮的id、class属性,或者用contains模糊匹配文本:
    # 模糊匹配文本
    Execute_Button = driver.find_element(By.XPATH, '//button[contains(text(), "Execute")]')
    # 假设按钮有id属性"execute-btn"
    Execute_Button = driver.find_element(By.ID, "execute-btn")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:41:39