首页 > 解决方案 > 如何使用 Selenium 和 Python 单击包含属性 focusable="false" 的 svg 标签的元素

问题描述

我对 Python 中的 Selenium 很陌生。这次我在点击一个元素时遇到了问题(这是一个关闭按钮)。

<div class="CloseButton_Background__27knc">
     <svg class="MuiSvgIcon-root CloseButton_Icon__7wksG" focusable="false" viewBox="0 0 24 24" 
      aria-hidden="true" style="font-size: 36px;">
        <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 
          19 19 17.59 13.41 12 19 6.41z"></path></svg></div> 

我首先要做的是:我正在网站上寻找一个元素:

closeButton = self.driver.find_elements_by_xpath('//div[@class="CloseButton_Background__27knc"]/*[name()="svg"][@class="MuiSvgIcon-root CloseButton_Icon__7wksG"]')

该元素位于页面上。然后我尝试调用click ()它的方法,我得到这个错误:

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

我正在等待按钮可见。请帮忙!谢谢!

标签: pythonseleniumxpathcss-selectorswebdriverwait

解决方案


可聚焦=“假”

根据在 SVG 中管理焦点中的文档:

focusableSVG Tiny 1.2 定义的属性仅在 Internet Explorer 和 Microsoft Edge 中实现。与tabindex此属性不同的是,该属性具有布尔值,其中focusable="true"等于tabindex="0"并使focusable="false"元素惰性。除了<a xlink:href="…&quot; focusable="false">通过<svg focusable="false">.


这个用例

要单击所需的元素,最好避免使用该<svg>标签,并且您必须诱导WebDriverWait并且element_to_be_clickable()您可以使用以下任一定位器策略

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div[class^='CloseButton_Background']"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[starts-with(@class, 'CloseButton_Background')]"))).click()
    
  • 注意:您必须添加以下导入:

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

参考

您可以在以下位置找到有关ElementNotInteractableException的一些相关讨论:


推荐阅读