Selecting and Identifying element with JQuery to use it in Selenium 2 Java API

后端 未结 3 1056
时光说笑
时光说笑 2020-12-09 14:02

This is the situation:

  • I use the Java API of Selenium 2 to open and control a firefox browser instance
  • I load the jQuery script to a page via JavaScri
相关标签:
3条回答
  • 2020-12-09 14:22

    Using eval makes it even easier. Use an index selector such as [0] with the jQuery code or it will return a collection of elements.

        String elementLocator = "$('#btnID')[0]";
        public RemoteWebElement getElementByJQueryLocator(String jQueryLocator){
            JavascriptExecutor js = (JavascriptExecutor) driver;
            RemoteWebElement element = (RemoteWebElement) js.executeScript("return eval(arguments[0]);", jQueryLocator);
            return element;
        }
    
            RemoteWebElement webElement = getElementByJQueryLocator(elementLocator);
            webElement.click();
    
    0 讨论(0)
  • 2020-12-09 14:24

    Not sure of your exact problem but you can build you locator using html id, name, class etc attributes.

    0 讨论(0)
  • 2020-12-09 14:29

    I found the solution, which is quite easy:

    String jQuerySelector = "'#myDiv input.test'";
    RenderedWebElement webElement = (RenderedWebElement) ((JavascriptExecutor) webDriver).executeScript("return $(" + jQuerySelector+ ").get(0);");
    

    Working with an element in jQuery which was previosly selected in Selenium works too:

    String jQuerySelector = "arguments[0]";
    ((JavascriptExecutor) webDriver).executeScript("return $(" + jQuerySelector+ ").doSomethingInJquery();", webElement);
    
    0 讨论(0)
提交回复
热议问题