【问题标题】:How to click not interactable dropdown with selenium and python and select one option?如何单击与 selenium 和 python 不可交互的下拉菜单并选择一个选项?
【发布时间】:2019-11-24 03:41:00
【问题描述】:

我有这个 ID 为“drp_autogen0”的下拉列表。我想单击下拉菜单以查看下拉选项。当我尝试使用 Python 和 Selenium 单击它时,出现此错误:selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable 我附上了下拉列表的打印屏幕。我希望能够从列表中选择“上个月”,但我还没有走那么远,因为没有点击下拉菜单。 https://snipboard.io/xDM1Un.jpg

下拉点击的代码在这里:

html_list = driver.find_element_by_id("drp_autogen0")
html_list.click()

下拉按钮的网页代码是:

<button type="button" class="comiseo-daterangepicker-triggerbutton ui-button ui-corner-all ui-widget comiseo-daterangepicker-bottom" id="drp_autogen0">22 Nov 2019<span class="ui-button-icon-space"> </span><span class="ui-button-icon ui-icon ui-icon-triangle-1-s"></span></button>

上个月的网页代码是:

<div id="ui-id-5" tabindex="-1" role="menuitem" class="ui-menu-item-wrapper">Last month</div>

【问题讨论】:

    标签: javascript python html selenium


    【解决方案1】:

    请检查 DOM 在运行时没有变化,如果没有,则有两种方法可以解决此异常:

    1.隐式等待

    driver.manage().timeouts().implicitly Wait(10, TimeUnit.SECONDS);
    

    2。 WebDriver 等待:

    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("<Element path>")));
    

    【讨论】:

      【解决方案2】:

      如果您收到 ElementNotInteractable 错误消息,您可以尝试使用 Javascript click 解决该问题:

      from selenium.webdriver.common.by import By
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      
      # first, wait for the button to exist
      html_list = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "drp_autogen0")))
      
      # now click with Javascript
      driver.execute_script("arguments[0].click();", html_list)
      
      # now, click last month -- wait for it to exist first!
      WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[text()='Last month']"))).click()
      

      此代码示例在您想要的元素上调用 WebDriverWait,以确保它们在单击之前已完全加载到页面上。

      然后,我们使用 Javascript 单击第一个 button 元素,以解决 ElementNotInteractable 异常。展开下拉菜单后,我们会等待 Last Month 选项存在,然后再尝试单击它。

      即使看起来按钮/下拉选项似乎立即出现在页面上,Selenium/Python 确实在 DOM 中快速移动,因此driver 可能正在尝试单击尚不存在的东西。 WebDriverWait 语句只是在尝试单击之前确保该元素存在于页面上。

      【讨论】:

        猜你喜欢
        • 2018-02-17
        • 2023-04-09
        • 2020-09-17
        • 2022-01-20
        • 2023-03-25
        • 2022-11-11
        • 2022-01-23
        • 2020-05-14
        • 2016-07-28
        相关资源
        最近更新 更多