简体   繁体   中英

Return value from a JQuery script in Selenium Webdriver

I have got a problem with obtaining some href's by Selenium Webdriver. Therefore I have used JQuery script to make it.

script = 
"(function() {
    var a = [];
    $("a.class0.class1.link").each(function() {
        a.push($(this).attr('href'));
    });
    return a;
})()";

executed by such code:

result = javascriptExecutor.executeScript(script)

But result has null value. When I run that script in Chrome console I have got correct result - array of href's. What I did wrongly?

Ok, I have solved problem. There are 2 ways of achieving result - obtaining href's from links.

script = "return $('a.class0.class1.link');"

execute such script and get an Array of WebElements from which it is possible to get attributes:

val js = browser.asInstanceOf[JavascriptExecutor]
val scriptResult = js.executeScript(script)
val result = ListBuffer.empty[String]

scriptResult.asInstanceOf[util.ArrayList[WebElement]].forEach(x => result +=
  x.getAttribute("href"))

result.toList

or in second way - execute such JQuery code:

val script = "return (function() {var table = [];$('a.class0.class1.link').each(function() { table.push($(this).attr('href'));});return table;})();"

and collect result:

val js = browser.asInstanceOf[JavascriptExecutor]
val scriptResult = js.executeScript(javascript)
scriptResult.asInstanceOf[util.ArrayList[String]].asScala.toList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM