如何使用JavaScript执行器获取网页标题
How to get the webpage title using JavaScript executor
我是自动化测试小白。在我的代码中,我在我的 Selenium 自动化测试脚本中使用 JavaScript(关于使用 JUnit)。我正在尝试查找当前 window 标题:
driver = new ChromeDriver();
js = (JavaScriptExecutor)driver;
driver.get(//passed url);
//after the log in my Org. I execute the command below
//to get the title of the current window I execute the below command
js.executeScript("document.getElementsByTagName('title').innerHTML;");
But the above command will return the answer as the null instant of
getting the title of the window. So does anyone know what's wrong with
my command?
但是我在页面的控制台日志上执行时得到了 window 的标题。所以我不知道我的代码有什么问题。
谢谢。
Mohan Raj S.
更改以下行:
document.getElementsByTagName('title').innerHTML
至:
return document.getElementsByTagName('title')[0].innerHTML
在代码中它将是:
js.executeScript("return document.getElementsByTagName('title')[0].innerHTML;");
getElementsByTagName returns 元素数组。所以我们需要传递索引值。
Web driver 界面提供获取标题的方法。很简单。
String title=driver.getTitle();
System.out.println("Title is" + title);
你也可以这样做
function titleCheck() {
promise = driver.getTitle();
promise.then(function(title) {
console.log("The title is: " + title);
});
}
参考:https://blog.testproject.io/2018/03/08/selenium-javascript-best-practices/
尽管他们的 var test- 东西对我不起作用,但我不得不将其删除。
JavascriptExecutor js = (JavascriptExecutor)driver;
String text = js.executeScript("return document.title;").toString();
我是自动化测试小白。在我的代码中,我在我的 Selenium 自动化测试脚本中使用 JavaScript(关于使用 JUnit)。我正在尝试查找当前 window 标题:
driver = new ChromeDriver();
js = (JavaScriptExecutor)driver;
driver.get(//passed url);
//after the log in my Org. I execute the command below
//to get the title of the current window I execute the below command
js.executeScript("document.getElementsByTagName('title').innerHTML;");
But the above command will return the answer as the null instant of getting the title of the window. So does anyone know what's wrong with my command?
但是我在页面的控制台日志上执行时得到了 window 的标题。所以我不知道我的代码有什么问题。
谢谢。
Mohan Raj S.
更改以下行:
document.getElementsByTagName('title').innerHTML
至:
return document.getElementsByTagName('title')[0].innerHTML
在代码中它将是:
js.executeScript("return document.getElementsByTagName('title')[0].innerHTML;");
getElementsByTagName returns 元素数组。所以我们需要传递索引值。
Web driver 界面提供获取标题的方法。很简单。
String title=driver.getTitle();
System.out.println("Title is" + title);
你也可以这样做
function titleCheck() {
promise = driver.getTitle();
promise.then(function(title) {
console.log("The title is: " + title);
});
}
参考:https://blog.testproject.io/2018/03/08/selenium-javascript-best-practices/
尽管他们的 var test- 东西对我不起作用,但我不得不将其删除。
JavascriptExecutor js = (JavascriptExecutor)driver;
String text = js.executeScript("return document.title;").toString();