[英]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 和 web 驅動程序的新手,因此將不勝感激。
要單擊元素,您必須為element_to_be_clickable()
誘導WebDriverWait ,並且您可以使用以下任一Locator Strategies :
使用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
您可以在以下位置找到一些關於NoSuchElementException的相關討論:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.