Node.js + Selenium如何正确parsinghtml
我想遍历页面上的所有元素:
th元素的path是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()); });
但是我得到:
drobazko@drobazko:~/www$ node first_test.js { then: [Function: then], cancel: [Function: cancel], isPending: [Function: isPending] }
相反,文字General
问题是:
1.如何获得正确的文本string?
2.我如何遍历许多要素?
1 – 如何获得正确的文本string?
driver.findElement(webdriver.By.xpath("//div[@id='specs-list']/table/tbody/tr/th")).getText().then(function(textValue){ console.log(textValue); });
要么
driver.findElement(webdriver.By.xpath("//div[@id='specs-list']/table/tbody/tr/th")).then(function(elem){ elem.getText().then(function(textValue) { console.log(textValue); }); });
为什么?
findElement和getText()都会返回您的承诺。 如果您尝试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); }); }); });
对不起,在这里问我的问题。 我真的需要答案。 我们怎样才能使用textValue的function。 我需要使用textValue与其他数据进行比较。