【问题标题】:How to automate elements without a class id in python selenium?如何在python selenium中自动化没有类ID的元素?
【发布时间】:2022-01-26 05:19:53
【问题描述】:

我正在尝试自动按下 selenium 中的以下按钮,但我习惯于使用它们的 ID 来引用元素。此按钮没有 ID:

<button type="button" class="button-error en-button" ng-transclude="" 
en-tap="AssignDateTime();showModal('utilities/assignment 
editior/delete',{item:item}, assignmentslist.refresh)" style="touch- 
action: manipulation; user-select: none; -webkit-user-drag: none; - 
webkit-tap-highlight-color: rgba(0, 0, 0, 0);">

<en-icon icon="trash" class="ng-scope">
</en-icon>
</button>

【问题讨论】:

  • 使用 css 选择器 .button-error.en-button ?

标签: python selenium selenium-webdriver automation


【解决方案1】:

到元素上的click(),您可以使用以下任一Locator Strategies

  • 使用css_selector

    driver.find_element(By.CSS_SELECTOR, "button.button-error.en-button[en-tap^='AssignDateTime'][en-tap*='assignmentslist']").click()
    
  • 使用xpath

    driver.find_element(By.XPATH, "//button[@class='button-error en-button' and starts-with(@en-tap, 'AssignDateTime')][contains(@en-tap, 'assignmentslist')]").click()
    

想要的元素是动态元素,所以点击该元素需要诱导WebDriverWaitelement_to_be_clickable(),可以使用以下Locator Strategies之一:

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.button-error.en-button[en-tap^='AssignDateTime'][en-tap*='assignmentslist']"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='button-error en-button' and starts-with(@en-tap, 'AssignDateTime')][contains(@en-tap, 'assignmentslist')]"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

【讨论】:

    【解决方案2】:

    你可以只使用类:

    driver.find_element_by_class_name('button-error').click()driver.find_element_by_class_name('en-button').click()

    如果您找到多个具有相同类名的元素,则使用 xpath

    //button[@class='button-error en-button'](//button[@class='button-error en-button'])[1]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      相关资源
      最近更新 更多