如何使用 Selenium 和 Python 按名称查找并单击页面中的按钮
How to find and click on a button in page by name using Selenium and Python
我想按名称或文本在页面中查找并单击按钮。
HTML:
<input name="ppw-widgetEvent:SetPaymentPlanSelectContinueEvent" class="a-button-input a-button-text" type="submit" aria-labelledby="pp-NKOnMC-86-announce">
代码试验:
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.NAME, "name']"))).click()
PS:我认为元素是动态的,在页面中有2个功能名称相同的按钮,因此我不能按名称使用元素。
如果页面上有 2 个具有相同 name
属性的按钮,您需要在构建将标识 uniquely within the DOM Tree.[=19 的定位器时合并一些独特的属性=]
解决方案
点击需要诱导的元素WebDriverWait 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.a-button-input.a-button-text[name='ppw-widgetEvent:SetPaymentPlanSelectContinueEvent'][aria-labelledby$='announce']"))).click()
使用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()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
我想按名称或文本在页面中查找并单击按钮。 HTML:
<input name="ppw-widgetEvent:SetPaymentPlanSelectContinueEvent" class="a-button-input a-button-text" type="submit" aria-labelledby="pp-NKOnMC-86-announce">
代码试验:
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.NAME, "name']"))).click()
PS:我认为元素是动态的,在页面中有2个功能名称相同的按钮,因此我不能按名称使用元素。
如果页面上有 2 个具有相同 点击需要诱导的元素WebDriverWait for the 使用 使用 注意:您必须添加以下导入:name
属性的按钮,您需要在构建将标识
解决方案
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.a-button-input.a-button-text[name='ppw-widgetEvent:SetPaymentPlanSelectContinueEvent'][aria-labelledby$='announce']"))).click()
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()
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC