简体   繁体   English

如何使用 Selenium 和 Python 按名称查找并单击页面中的按钮

[英]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: 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. PS:我认为元素是动态的,并且在页面中停留 2 按钮具有相同的 function e 名称,因此我不能按名称使用元素。

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 .如果页面上有 2 个具有相同name属性的按钮,您需要在构造定位器时加入一些唯一属性,该定位器将在DOM Tree中唯一标识WebElement


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 :要单击元素,您需要为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.a-button-input.a-button-text[name='ppw-widgetEvent:SetPaymentPlanSelectContinueEvent'][aria-labelledby$='announce']"))).click()
  • Using XPATH :使用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

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

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