javascript - 我们如何确定何时在 selenium c# 中使用 JavaScriptExecutor?

标签 javascript c# selenium selenium-webdriver page-title

TestInChrome1 抛出异常 - “OpenQA.Selenium.ElementNotInteractableException:元素不可交互”但是,当在 TestInChrome2 中使用 JavaScriptExecutor 时,它运行良好。

我的问题是:

  1. 为什么 Click() 方法在 TestInChrome1 中不起作用?

  2. 如何在不反复试验的情况下确定 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>内。因此,该标签的信息是可见可读,但不是可交互

page_title

<小时/>

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/

相关文章:

javascript - 在数据库中存储表单架构和函数

python - 如何在某些文本之前将 XPath 写入文本?

javascript - 字符串引用的对象未显示

c# - 在 ServiceStack 的 Ormlite 中处理日期和日期时间

c# - .NET 中的 Xml 序列化

c# - 如何在 C# 中的 ActionLink html 帮助程序中指定 Controller

java - 如何使用 selenium webdriver 在 chrome 中下载 pdf 文件

java - 如何等待警报框在Selenium中执行操作?

javascript - 选择按钮后自动播放音频

javascript - 使用 PHP $_GET 执行 JavaScript 代码