如何关闭遮挡其他元素的永久元素?

How to close a permanent element obscuring other elements?

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

在 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 Example

我曾尝试使用 IDE 中的 select 函数来识别未包含在下拉菜单中的其他元素。我也尝试过使用 firebug。但这是唯一可以在下拉菜单之外单击的元素。

Firebug view

总结一下:

  1. 如果我发送"Esc"的代码不正确,请告诉我。

  2. 为什么 Visual Studio 无法识别并单击 //div[3]/div[3],即在下拉菜单之外,而在 Selenium IDE 中可以做到这一点?

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

  4. 我了解到您始终可以单击使用 javascript 遮挡的元素,但我还没有找到如何在 C# 中执行此操作的指南。请告诉我你们是否知道该怎么做。

我总是尝试 select 通过使用 xpath 或直接 css 列表项而不是单击列表框和 selecting 来 select 列表项。这样我们就可以忽略这个麻烦,而且速度也更快。 怎么做:

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);

这种情况下的解决方案是单击遮挡页面其余部分的元素:

driver.FindElement(By.CssSelector(".cdk-overlay-backdrop.cdk-overlay-transparent-backdrop.cdk-overlay-backdrop-showing")).Click();

当我这样做时,下拉菜单关闭了。

注意:我必须为 CSSSelector 使用另一种格式才能识别元素。

在我之前得到的错误信息中,模糊元素是这样写的 Visual Studio:

cdk-overlay-backdrop cdk-overlay-transparent-backdrop cdk-overlay-backdrop-showing

但我无法将其复制到 CSSSelector 中,似乎您总是必须添加一个“.”在 CSSSelector Id 的开头,并将元素名称中的所有空格替换为“.”

像这样:

.cdk-overlay-backdrop.cdk-overlay-transparent-backdrop.cdk-overlay-backdrop-showing