【问题标题】:How to find a button in selenium?(Python)如何在硒中找到一个按钮?(Python)
【发布时间】:2021-10-04 07:56:21
【问题描述】:

我想在 selenium 中找到这个按钮:

<input class="button button-primary" type="submit" value="Send me the code" data-type="save">

我试过了:

driver.find_element_by_xpath("//input[@value='Send me the code']").click()

但这没有用。

【问题讨论】:

  • 错误是什么?
  • 如果没有找到按钮可能会被放置在 iframe 中,这意味着您需要先切换到该框架才能搜索按钮
  • @cruisepandey 没有错误,但它没有点击按钮
  • @AtomStore : 请见下文。

标签: python python-3.x selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

在 Selenium 中基本上有 4 种点击方式。

我将使用这个 xpath

//input[@value='Send me the code']

代码试用 1:

time.sleep(5)
driver.find_element_by_xpath("//input[@value='Send me the code']").click()

代码试用 2:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@value='Send me the code']"))).click()

代码试用 3:

time.sleep(5)
button = driver.find_element_by_xpath("//input[@value='Send me the code']")
driver.execute_script("arguments[0].click();", button)

代码试用 4:

time.sleep(5)
button = driver.find_element_by_xpath("//input[@value='Send me the code']")
ActionChains(driver).move_to_element(button).click().perform()

进口:

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

PS:如果我们在HTML DOM 中有唯一条目,请检查dev tools(谷歌浏览器)。

检查步骤:

Press F12 in Chrome -> 转到element 部分 -> 做一个CTRL + F -> 然后粘贴xpath 看看,如果你想要的element 用@ 得到突出显示 987654334@匹配节点。

【讨论】:

    【解决方案2】:

    driver.find_element_by_xpath("//input[@value='Send me the code']").click() 这样的简单代码行可能无法正常工作的原因有很多。
    最可能的原因可能是错过了等待/延迟。您应该等到元素完全加载后再尝试访问它。而不是使用driver.find_element_by_xpath("//input[@value='Send me the code']").click() 请尝试这样的事情:

    wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@value='Send me the code']"))).click()
    

    要使用它,您需要以下导入:

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

    并初始化wait对象

    wait = WebDriverWait(driver, 20)
    

    定位器也可能不是唯一的。
    该元素也可以位于 iframe 等内部。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2023-03-26
      • 2016-06-02
      • 1970-01-01
      相关资源
      最近更新 更多