Node.js + Selenium如何正确解析html [英] Node.js + Selenium How to parse html properly

查看:266
本文介绍了Node.js + Selenium如何正确解析html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历页面上的所有 th 元素:

I would like to traverse through all th elements on my page:

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());
});

但是我得到:

drobazko@drobazko:~/www$ node first_test.js
{ then: [Function: then],
  cancel: [Function: cancel],
  isPending: [Function: isPending] }

代替文字General 问题是:
1.如何获取正确的文本字符串?
2.如何遍历许多 th 元素?

Instead text General Questions are:
1. How can I get correct text string?
2. How Can I traverse through many th elements?

推荐答案

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

1 - How can I get correct text 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(....))

Both findElement and getText() return you a promise. You would get similar result if you try to console.log(driver.findElement(....))

2-如何遍历许多要素?

2 - How Can I traverse through many th elements?

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);
        });
    });
});

这篇关于Node.js + Selenium如何正确解析html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆