Selenium无法定位xpath,但是xpath在浏览器中



我不确定这是否是最好的标题,但我不确定如何描述它,我正试图使用selenium在网站上自动执行2fa,所以我所需要做的就是接听电话,脚本会处理剩下的事情。然而,我试图让selenium点击的按钮一直显示为无法定位,尽管它总是在同一个地方,而且从未更改。这是我在python 中的代码

callMe = driver.find_element('xpath', '//*[@id="auth_methods"]/fieldset/div[2]/button')
callMe.click()
sleep(25)

这是三个按钮中的一个,除了xpath之外,它们都有相同的元素信息。这里是我试图获取第二个的所有三个按钮元素

<button tabindex="2" type="submit" class="positive auth-button"><!-- -->Send Me a Push </button>
<button tabindex="2" type="submit" class="positive auth-button"><!-- -->Call Me </button>
<button tabindex="2" type="submit" class="positive auth-button"><!-- -->Text Me </button>

我不确定除了使用xpath之外,我还能如何找到第二个按钮,但这不起作用,我不知道我是否可以,也不知道如何根据里面的文本搜索按钮。

您尝试过By吗?

from selenium.webdriver.common.by import By
callMe = driver.find_element(By.XPATH, '//*[@id="auth_methods"]/fieldset/div[2]/button')

尝试使用By.cssselector,获取所需按钮的主体html的css选择器。

callMe = driver.find_element(By.css_selector, 'selectorofbodyhtml')
callme.click()

在xpath 下尝试

//button[starts-with(text(),'Call Me')]

所需的元素Call Me是一个动态元素,因此要点击它,您需要诱导WebDriverWait等待元素_to_be_clickle(),您可以使用以下定位器策略之一

  • 使用XPATHcontains()

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(., 'Call Me')]"))).click()
    
  • 使用XPATHstarts-with()

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[starts-with(., 'Call Me')]"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

最新更新