单击使用硒的网站上的按钮

Click a button on a website using selenium

我正在尝试使用 selenium 单击网站上的按钮。 这是 html:

<form action="/login/" id="login" method="post" class="form-full-width">
   <input data-testid="loginFormSubmit" type="submit" class="btn btn-success btn-large" value="Log in" 
   tabindex="3">
</form>

这是我的一些代码:

if __name__ == "__main__":
    driver = webdriver.Chrome()
    wait = WebDriverWait(driver, 100)
    driver.get ('https://www.url.com/login/')
    driver.find_element_by_name('username').send_keys('username')
    driver.find_element_by_name('password').send_keys('password')
    driver.find_elements_by_xpath("//input[@value='Log in' and @type='submit']")

我也试过:

driver.find_element_by_value('log in').click()
driver.find_element_by_xpath("//a[@href='https://www.url.com/home/']").click()

然而当我运行它时,它总是出现这个错误信息:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@href='https://www.url.com/home/']"}

我是 selenium 和网络驱动程序的新手,所以任何帮助将不胜感激。

要点击你要诱导的元素 for the element_to_be_clickable() and you can use either of the following :

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[data-testid='loginFormSubmit'][value='Log in']"))).click()
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@data-testid='loginFormSubmit' and @value='Log in']"))).click()
    
  • 注意:您必须添加以下导入:

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

参考资料

您可以在 中找到一些相关讨论: