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
相关产品推荐
相关产品推荐

