简体   繁体   中英

How to find and click on a button in page by name using Selenium and Python

I want to find and click a button in a page by name or text. HTML:

<input name="ppw-widgetEvent:SetPaymentPlanSelectContinueEvent" class="a-button-input a-button-text" type="submit" aria-labelledby="pp-NKOnMC-86-announce">

Code trials:

WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.NAME, "name']"))).click()

PS: I think the element is dynamic, and in page stay 2 button with same function e name, therefore I can't use element by name.

In case there are 2 buttons with the same name attribute on the page you need to club up some of the unique attribute while constructing the locator which will identify the WebElement uniquely within the DOM Tree .


Solution

To click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies :

  • Using CSS_SELECTOR :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.a-button-input.a-button-text[name='ppw-widgetEvent:SetPaymentPlanSelectContinueEvent'][aria-labelledby$='announce']"))).click()
  • Using XPATH :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='a-button-input a-button-text' and @name='ppw-widgetEvent:SetPaymentPlanSelectContinueEvent'][contains(@aria-labelledby, 'announce')]"))).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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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