首页 > 解决方案 > 使用 selenium python 单击元素时出现问题

问题描述

我正在尝试使用 selenium 和 python 单击网页上的元素

driver.find_element_by_class_name("market-selection.ng-scope").click()

但我得到元素不可点击的错误

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

这是元素 html(它不在框架中);我猜可交互的部分是第二个 div 但我也尝试了其他两个以防万一......

<div class="market-selection-container 18" ng-repeat="market in wrapperCategoryGroup.currentMacroCategoria.mkl track by $index">
      <!-- ngIf: wrapperCategoryGroup.marketTypes[market].nm    -->
      <div class="market-selection ng-scope" ng-if="wrapperCategoryGroup.marketTypes[market].nm" ng-class="{'active':wrapperCategoryGroup.currentMarketType == market}" ng-click="wrapperCategoryGroup.getMarketType(market)" style="">
        <span class="ng-binding">
          doppia chance 
        </span>
      </div>
    <!-- end ngIf: wrapperCategoryGroup.marketTypes[market].nm -->
 </div>

有什么提示吗?

标签: pythonseleniumxpathcss-selectorswebdriverwait

解决方案


要单击带有文本保存的元素,您可以使用以下任一定位器策略

  • 使用css_selector

    driver.find_element_by_css_selector("div.market-selection.ng-scope > span.ng-binding").click()
    
  • 使用xpath

    driver.find_element_by_xpath("//div[@class='market-selection ng-scope']/span[@class='ng-binding' and contains(., 'doppia chance')]").click()
    

理想情况下,要单击需要诱导WebDriverWait的元素element_to_be_clickable(),您可以使用以下任一Locator Strategies

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.market-selection.ng-scope > span.ng-binding"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='market-selection ng-scope']/span[@class='ng-binding' and contains(., 'doppia chance')]"))).click()
    
  • 注意:您必须添加以下导入:

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

推荐阅读