【问题标题】:How to find and click on a button in page by name using Selenium and Python如何使用 Selenium 和 Python 按名称查找并单击页面中的按钮
【发布时间】:2020-12-20 17:33:43
【问题描述】:

我想按名称或文本在页面中查找并单击按钮。 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个按钮具有相同的功能e名称,因此我不能按名称使用元素。

【问题讨论】:

  • 按名称查找元素要求元素具有名称属性,例如&lt;input type="button" name="foo"&gt;
  • 按钮是这样的:
  • 我认为是动态的,并且在页面中停留 2 按钮具有相同的功能 e 名称,因此我不能按名称使用元素...

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:

如果页面上有 2 个具有相同 name 属性的按钮,您需要在构建定位器时加入一些唯一属性,该定位器将在 DOM Tree 中唯一标识 WebElement


解决方案

点击元素需要诱导WebDriverWaitelement_to_be_clickable(),可以使用以下Locator Strategies之一:

  • 使用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
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2020-10-03
    • 2018-12-27
    • 2021-06-30
    • 2023-02-07
    • 2018-08-22
    相关资源
    最近更新 更多