首页 > 解决方案 > 即使 WebElement 不可见,is_displayed() 方法也会返回 true

问题描述

我正在进行一项测试,该测试在某些时候记录了可滚动表中显示的一些数据:

<div class='table-body'>
   <div class='scroll-wrapper>
      <div class='row'>
         <button class='button' type='button'></button>
         <div class='inner-data></div>
      </div>
      <div class='row'>
         <button class='button' type='button'></button>
         <div class='inner-data></div>
      </div>
      <div class='row'>
         <button class='button' type='button'></button>
         <div class='inner-data></div>
      </div>
   </div>
</div>

表格中存在的总行数显示在屏幕上,允许我使用while循环来确保收集所有数据。但是,正如您在 html 代码中看到的那样,每一行都有一个我正在为每一行单击的按钮。这是我的问题:在某些时候,我的方法find_elements_by_css_selector(div.row)找到了一个在窗口上不可见的 WebElement ,并尝试单击它的<button>. 因此,我收到以下错误:

ElementNotInteractableException: Message: Element <button class="btn" type="button"> could not be scrolled into view

我尝试使用is_displayed()方法并is_enabled()检查元素是否在屏幕上可见,不幸的是它们总是返回True

各位有什么解决办法吗?

标签: pythonpython-3.xseleniumselenium-webdriverautomated-tests

解决方案


此错误消息...

ElementNotInteractableException: Message: Element <button class="btn type="button"> could not be scrolled into view

...意味着所需的元素无法滚动到视图中并且不可交互。

如果您观察相关的 HTML,则<button>标签为:

<button class='button' type='button'></button>

它们在父<div>标签内,如下所示:

<div class='row'>

您已使用Locator Strategy 定位<div>标签:

find_elements_by_css_selector(div.row)

但是ElementNotInteractableException对于其他一些元素会返回错误:

<button class="btn      type="button">
observe the ^^^class^^^ attribute value

这不是你想要的元素。因此,您会看到错误。


解决方案

作为针对<button>标签的解决方案,您需要更深入地挖掘进一步诱导WebDriverWaitvisibility_of_all_elements_located()单击每个元素,您可以使用以下任一 定位器策略

  • 使用CSS_SELECTOR

    for element in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "div.table-body > div.scroll-wrapper div.row > button.button[type='button']"))):
        WebDriverWait(driver, 20).until(EC.visibility_of(element)).click()
    
  • 使用XPATH

    for element in WebDriverWait(driver, 30).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='table-body']/div[@class='scroll-wrapper']//div[@class='row']/button[@class='button' and @type='button']"))):
        WebDriverWait(driver, 20).until(EC.visibility_of(element)).click()
    
  • 注意:您必须添加以下导入:

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

推荐阅读