首页 > 解决方案 > 如何关闭遮挡其他元素的永久元素?

问题描述

我无法单击某个元素,因为下拉菜单会遮挡所有其他元素。

在 Visual Studio 中使用 Selenium,我正在尝试构建一个测试用例,我首先单击下拉菜单中的复选框,然后单击下拉菜单之外的另一个元素。但是,单击第一个复选框后,下拉菜单不会自行关闭。

如果您在网络浏览器上手动关闭此下拉菜单,您只需按 Esc 或单击下拉菜单外的某个位置。但是当我尝试自动化它时它不起作用。

我曾尝试在脚本中像这样按 Esc 键:

Actions action = new Actions(driver);
action.SendKeys(OpenQA.Selenium.Keys.Escape);

但它不起作用。当尝试单击被遮挡的元素时,它不会发送有关发送 Esc 键的错误,而是在下一行发送超时:

OpenQA.Selenium.ElementClickInterceptedException : Element <div class="mat-radio-outer-circle"> is not clickable at point (116,608) because another element <div class="cdk-overlay-backdrop cdk-overlay-transparent-backdrop cdk-overlay-backdrop-showing"> obscures it

我也尝试过在下拉菜单之外单击而不是发送 Esc 键,如下所示:

wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[3]/div[3]"))).Click();

这在 Visual Studio 中不起作用,但它在 Selenium IDE 中起作用,只需使用命令单击并设置//div[3]/div[3]为目标。

Selenium IDE 示例

我尝试使用 IDE 中的选择功能来识别下拉菜单中未包含的其他元素。我也尝试过使用萤火虫。但这是在下拉菜单之外唯一可点击的元素。

萤火虫视图

总结一下:

  1. 请告诉我发送“Esc”的代码是否不正确。

  2. 当可以在 Selenium IDE 中执行此操作时,为什么 Visual Studio 无法识别并单击//div[3]/div[3]下拉列表之外的 ie?

  3. 还有其他方法可以关闭下拉菜单吗?

  4. 我已经读到您总是可以单击使用 javascript 隐藏的元素,但我还没有找到如何在 C# 中执行此操作的指南。请告诉我,如果你们知道如何做到这一点。

标签: c#cssseleniumelementsendkeys

解决方案


我总是尝试通过使用列表项的 xpath 或 css direct 来选择列表项,而不是单击列表框并进行选择。通过这种方式,我们可以忽略这个麻烦,它也更快。怎么做:

driver.FindElement(By.Xpath("//select[@attribute='attributeValue']/li[@attribute='attributeValue'])).click

这是Javascript方法。参考以下 2 个链接https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/JavascriptExecutor.html

https://seleniumhq.github.io/selenium/docs/api/dotnet/html/M_OpenQA_Selenium_IJavaScriptExecutor_ExecuteScript.htm

IWebDriver driver; // assume assigned elsewhere
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// if you want to click on element
IWebElement element = driver.FindElement(By.CssSelector("your css locator goes here")) 

// if you want to return value from javascript and store
string title = (string)js.ExecuteScript("return document.title");

如果你想隐藏隐藏元素,这里是使用js的逻辑。

element = driver.FindElement(By.Xpath("//div[@class='cdk-overlay-backdrop cdk-overlay-transparent-backdrop cdk-overlay-backdrop-showing']")); // this is the obscuring element in your case.
js.ExecuteScript("arguments[0].setAttribute("style","display: none;");",element);

推荐阅读