TestInChrome1 抛出异常 - “OpenQA.Selenium.ElementNotInteractableException:元素不可交互”但是,当在 TestInChrome2 中使用 JavaScriptExecutor 时,它运行良好。
我的问题是:
为什么 Click() 方法在 TestInChrome1 中不起作用?
如何在不反复试验的情况下确定 JavaScriptExecutor 是必要的?
[TestMethod] public void TestInChrome1() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://ultimateqa.com/"); IWebElement element = driver.FindElement(By.TagName("title")); element.Click(); driver.Quit(); } [TestMethod] public void TestInChrome2() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://ultimateqa.com/"); IWebElement element = driver.FindElement(By.TagName("title")); IJavaScriptExecutor js = (IJavaScriptExecutor)driver; string title = (string)js.ExecuteScript("return document.title"); driver.Quit(); }
最佳答案
<title>
所有 HTML 文档中都需要标签,它定义文档的标题。元素:
- 定义浏览器工具栏中的标题。
- 在将页面添加到收藏夹时提供页面标题。
- 在搜索引擎结果中显示页面的标题。
Note A: You can NOT have more than one element in an HTML document.
Note B: If you omit the
<title>
tag, the document will not validate as HTML.
如果您观察HTML DOM任何网站,例如https://ultimateqa.com/您将观察到 <title>
位于<head>
内。因此,该标签的信息是可见且可读,但不是可交互。
TestInChrome1()
根据上面的讨论,在TestInChrome1()
中:
您将无法调用
Click()
在标题标签上。要提取标题,您可以使用 Title属性来自 IWebDriver界面,您可以使用以下解决方案:
Console.WriteLine(driver.Title);
TestInChrome2()
现在您必须知道Selenium除了允许用户模拟最终用户执行的常见事件、在字段中输入文本、选择下拉值和复选框以及单击文档中的链接之外,它还提供许多其他控件,例如任意 JavaScript 执行。提取<title>
您可以使用 ExecuteScript()
方法来自 IJavaScriptExecutor界面如下:
Console.WriteLine((string)((IJavaScriptExecutor)driver).ExecuteScript("return document.title"));
关于javascript - 我们如何确定何时在 selenium c# 中使用 JavaScriptExecutor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59279456/