result of jsExecuteScript is null in Java while result in browser console is a String value

huangapple go评论79阅读模式
英文:

result of jsExecuteScript is null in Java while result in browser console is a String value

问题

https://www.companyfolders.com/proofs

当我在上述页面在浏览器控制台中运行脚本时:

document.querySelector('.subscribe_form input').value

我将看到占位符值作为运行结果:
"输入您的电子邮件地址"

但是当我尝试在Java中执行这个操作时:
我导航到这个页面然后尝试执行:

JavascriptExecutor js = (JavascriptExecutor) driver;
String emailPlaceholder = String.valueOf(js.executeScript("document.querySelector('.subscribe_form input').value"));

我总是看到执行的结果是 'null',或者如果我使用 .toString() 或转换为 (String) 会出现 NullPointerException。

NullPointerException

你有什么想法我在做错了什么?或者为什么这个脚本在Java Selenium中不起作用?

英文:

https://www.companyfolders.com/proofs

when I'm running a script in the browser's console on the above page:

document.querySelector('.subscribe_form input').value

I see the placeholder value as a result of running:
"Enter your email address"

but when I'm trying to do this in Java:
I'm navigating to this page then trying to execute:

JavascriptExecutor js = (JavascriptExecutor)driver;
String emailPlaceholder = String.valueOf(js.executeScript("document.querySelector('.subscribe_form input').value"));

I always see 'null' as a result of execution or NullPointerException if I'm using .toString() or casting to (String)

NullPointerException

any ideas what I'm doing wrong? or why this script doesn't work in Java selenium?

答案1

得分: 0

在 JavaScript 语句中加入一个返回语句

js.executeScript("return document.querySelector('.subscribe_form input').value")
                      ^^^^^^

如果脚本具有返回值(即脚本包含 return 语句),则将执行以下步骤:...

浏览器控制台会对返回值进行隐式打印。浏览器控制台是为人类开发的。为此,浏览器将尝试以人类可理解的方式打印返回值。因为在浏览器控制台键入 JavaScript 语句时,这很可能是您想要看到的内容。然而,Selenium 的 JavaScript 执行器不遵循这种设计理念。相反,您必须显式地使用 return。

英文:

put a return in the javascript statement

js.executeScript("return document.querySelector('.subscribe_form input').value")
                  ^^^^^^

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/JavascriptExecutor.html

> If the script has a return value (i.e. if the script contains a return statement), then the following steps will be taken: ...

The browser console does an implict print of the return value. The browser console is developed for humans. To that end the browser will try to print a sensible representation of a return value for the human. Because that is what you most likley wanted to see when you type javascript statements in the browser console. The selenium js executor does not follow that design philosophy. Instead you have to do an explicit return.

huangapple
  • 本文由 发表于 2020年9月30日 23:00:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/64140386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定