简体   繁体   English

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

[英]Click a button on a website using selenium

I am trying to click a button on a website using selenium.我正在尝试使用 selenium 单击网站上的按钮。 Here's the html:这是 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>

Here's some of my code:这是我的一些代码:

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']")

I have also tried:我也试过:

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

However when I run it, it always comes up with this error message:但是,当我运行它时,它总是会出现以下错误消息:

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

I am new to selenium and web drivers, so any help would be appreciated.我是 selenium 和 web 驱动程序的新手,因此将不胜感激。

To click on the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies :要单击元素,您必须为element_to_be_clickable()诱导WebDriverWait ,并且您可以使用以下任一Locator Strategies

  • Using CSS_SELECTOR :使用CSS_SELECTOR

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

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

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

References参考

You can find a couple of relevant discussions on NoSuchElementException in:您可以在以下位置找到一些关于NoSuchElementException的相关讨论:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM