node + selenium-webdriver 进行Web自动化测试

6,184 阅读1分钟

1、环境安装

nodejs安装

webdriver安装,安装各浏览器的驱动,通过各浏览器的驱动程序,操作浏览器。

chrome 驱动安装

每个版本的浏览器用到的webdriver不同。可以通过chrome右上角-> 帮助 -> 关于 Chrome 查看当前版本。

chromedriver下载地址和chromedriver与chrome之间的对应关系。跳转门

并将驱动程序所在目录添加至环境变量

其他浏览器驱动可以见下面列表:

2、代码实现自动化测试

npm init

npm install selenium-webdriver

// index.js
const {Builder, By, Key, until} = require('selenium-webdriver');
const {Options} = require('selenium-webdriver/chrome');
 
 
var driver = new Builder()
    .forBrowser('chrome')
    .setChromeOptions(new Options().excludeSwitches(["ignore-certificate-errors", 'user-data-dir="C:\\Users\\qiang\\AppData\\Local\\Google\\Chrome\\User Data"']))
    .build();
 
driver.get('https://image.baidu.com/')
    .then(function () {
        driver.findElement(By.id('search')).then(async (res)=>{
            console.log('res',await res.getText())
    })
    }).catch(function (e) {
    console.log(e);
});

3、By XPATH和CSS定位比较

4、参考文章:

Selenium WebDriver(一)

Selenium-Node.js:webdriver的用法

Selenium-webdriver基本使用

Selenium-WebDriver框架常用基本操作

【WebDriver】selenium使用CSS定位页面元素