eclipse 如何使用 jQuery 单击带有 Java 的 Selenium WebDriver 中的按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12086024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 18:50:55  来源:igfitidea点击:

How to click a button in Selenium WebDriver with Java using jQuery

javajqueryeclipseselenium-webdrivertestng

提问by Ripon Al Wasim

I have the following HTML:

我有以下 HTML:

<button class="gbqfba" name="btnK" aria-label="Google Search" id="gbqfba"><span id="gbqfsa">Google Search</span></button>

My following code for clicking "Google Search" button is working well using java in WebDriver:

我的以下用于单击“Google 搜索”按钮的代码在 WebDriver 中使用 java 运行良好:

driver.findElement(By.id("gbqfb")).click();

I want to use jQuery with WebDriver to click the button. How can I do it?

我想在 WebDriver 中使用 jQuery 单击按钮。我该怎么做?

I did the following (Test was run in eclipse by using TestNG framework):

我做了以下(测试是通过使用 TestNG 框架在 eclipse 中运行的):

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("$('#gbqfba').click();");

Unfortunately the following error was displayed:

不幸的是,显示了以下错误:

org.openqa.selenium.WebDriverException: $ is not defined (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 23 milliseconds

org.openqa.selenium.WebDriverException:$ 未定义(警告:服务器未提供任何堆栈跟踪信息)命令持续时间或超时:23 毫秒

What's the wrong with my above code?

我上面的代码有什么问题?

采纳答案by oshea00

WebDriver doesn't apparently use jQuery extension, so '$' isn't in the name space. You could load the minified jQuery.js into a string, then eval it as part of your test - which would add '$' to page's namespace...

WebDriver 显然没有使用 jQuery 扩展,所以 '$' 不在命名空间中。您可以将缩小的 jQuery.js 加载到一个字符串中,然后将其作为测试的一部分进行评估 - 这会将 '$' 添加到页面的命名空间...

回答by Ripon Al Wasim

The following code works nicely:

以下代码运行良好:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
URL jqueryUrl = Resources.getResource("jquery-1.8.2.min.js");
String jqueryText = Resources.toString(jqueryUrl, Charsets.UTF_8);
jse.executeScript(jqueryText);
jse.executeScript("$('#gbqfba').click();");

回答by Santhosh Raja

This could also be solved using List of classes

这也可以使用类列表来解决

List w = driver.findElements( By.cssSelector("button.gbqfba"));

List w = driver.findElements( By.cssSelector("button.gbqfba"));

    for(WebElement s1: w)
    {
        String s2= s1.getText();
        System.out.println(s2);

        if(s2.contentEquals("Google Search"))
        {
            s1.click();   
            break;
        }
    }