python - 即使 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。
各位有什么解决办法吗?
解决方案
此错误消息...
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>
标签的解决方案,您需要更深入地挖掘进一步诱导WebDriverWait并visibility_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
推荐阅读
- sql - 分组和替换
- git - 如何在不切换分支的情况下检查另一个分支中是否有新提交?
- python - 我无法在 pygame 中移动我的播放器,你知道为什么吗?
- php - 无法从 smsgateway.me 循环受保护的对象
- spring-integration - 监控动态集成流
- android - 无法在 Android Studio 3.3 Beta 2 中下载 groovy-all.jar (org.codehaus.groovy:groovy-all:2.4.15)
- c# - 尝试使用具有相同连接字符串的多个 DbContext 创建 TransactionScope 时出现 PlatformNotSupportedException
- java - 需要正则表达式来解析多行环境变量
- javascript - Javascript过滤器不仅按选择过滤?
- r - 如何在 R 中表示时间间隔