Node.js + Selenium如何正确解析html

Les*_*iev 1 selenium parsing node.js

我想通过所有穿越我的页面上的元素:

在此输入图像描述

th元素的路径是div [id ='specs-list']/table/tbody/tr/th:

我的脚本是:

var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder().
    withCapabilities(webdriver.Capabilities.chrome()).
    build();

driver.get('http://www.gsmarena.com');
driver.findElement(webdriver.By.name('sName')).sendKeys('iphone 4s');
driver.findElement(webdriver.By.id('quick-search-button')).click();


driver.findElement(webdriver.By.xpath("//div[@id='specs-list']/table/tbody/tr/th")).then(function(elem){
    console.log(elem.getText());
});
Run Code Online (Sandbox Code Playgroud)

但我得到:

drobazko@drobazko:~/www$ node first_test.js
{ then: [Function: then],
  cancel: [Function: cancel],
  isPending: [Function: isPending] }
Run Code Online (Sandbox Code Playgroud)

相反,文本General 问题是:
1.如何获得正确的文本字符串?
2.如何穿越的许多要素是什么?

Ngu*_*ang 5

1 - 如何获得正确的文本字符串?

driver.findElement(webdriver.By.xpath("//div[@id='specs-list']/table/tbody/tr/th")).getText().then(function(textValue){
    console.log(textValue);
});
Run Code Online (Sandbox Code Playgroud)

要么

driver.findElement(webdriver.By.xpath("//div[@id='specs-list']/table/tbody/tr/th")).then(function(elem){
    elem.getText().then(function(textValue) {
        console.log(textValue);
    });
});
Run Code Online (Sandbox Code Playgroud)

为什么?

findElement和getText()都会返回一个promise.如果你尝试console.log(driver.findElement(....))你会得到类似的结果

2 - 如何遍历许多元素?

driver.findElements(webdriver.By.xpath("//div[@id='specs-list']/table/tbody/tr/th")).then(function(elems){
    elems.forEach(function (elem) {
        elem.getText().then(function(textValue){
            console.log(textValue);
        });
    });
});
Run Code Online (Sandbox Code Playgroud)