JavaScript-使用selenium-webdriver将内部html返回给变量

JavaScript - Using selenium-webdriver what returns the inner html to a variable?

本文关键字:返回 变量 html 内部 使用 selenium-webdriver JavaScript-      更新时间:2023-09-26

以下是我在过去的Python项目中尝试过的几个例子(这里我使用的是JavaScript)。。。

var eltext = driver.findElement(webdriver.By.className('el')).text;
console.log(elname);
var eltext = driver.findElement(webdriver.By.className('el')).innerText;
console.log(elname);
var eltext = driver.findElement(webdriver.By.className('el')).innerHTML;
console.log(elname);

我还尝试了使用String()JSON.stringify()和各种for循环的其他方法,在我的选项上进行了旋转。我可以做一个.click(),这个对象是可点击的,所以我知道我的选择器是对的,但在JavaScript中访问内部文本是个问题。

以下是如何做到这一点:

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
   withCapabilities(webdriver.Capabilities.chrome()).
   build();
driver.get('http://www.example.com');
var el = driver.findElement(webdriver.By.tagName('div'));
// Get the text of the element using getText...
el.getText().then(function (text) {
    console.log(text);
});
// The code above could be shortened to this:
// el.getText().then(console.log);
// Get the inner HTML of the element using getInnerHtml...
el.getInnerHtml().then(function (html) {
    console.log(html);
});
// The code above could be shortened to this:
// el.getInnerHtml().then(console.log);
// Get the text browser side plus the innerHTML at the same time.
driver.executeScript(''
var el = arguments[0];'
return {text: el.innerText, html: el.innerHTML};'
', el).then(function (val) {
    console.log(val.text);
    console.log(val.html);
});
driver.quit();

您必须使用.then,因为方法本身不返回值,而是返回promise来获取值。

最后一个使用executeScript的方法同时获得这两个值。如果您想知道为什么要使用executeScript,原因是对getTextgetInnerHtml的每次调用都意味着Selenium客户端(您的脚本)和Selenium服务器(浏览器)之间的往返。在大型测试套件上,这些往返行程会累积起来,并会给套件的运行时间增加分钟。我还把它放在那里,以表明通过使用这种方法,你可以在浏览器上运行任何你想要的JavaScript。

您处理的是Selenium的WebElement,而不是DOM Element,所以不要尝试使用您从浏览器中知道的DOM API。硒是另一双鞋。

Selenium web驱动程序文档指向getText()getInnerHtml()