selenium-webdriver使用教程

环境准备:

  1. 安装 nodejs,版本:v8.9.4
  2. 下载 chromedriver
  3. 将 chromedriver 加入到 path 环境变量中
  4. npm i -S selenium-webdriver

示例代码:

const webdriver = require('selenium-webdriver')

async function openPage (targetPage) {
    console.log(`正在验证"${targetPage.name}": ${targetPage.url}`)
    const driver = new webdriver.Builder().forBrowser(webdriver.Browser.CHROME).build()
    await driver.get(targetPage.url)
    await driver.sleep(1000)
    driver.close()
}

async function main () {
    const targetPage = { name: '百度', url: `https://www.baidu.com/` }
    await openPage(targetPage)
}

main().then(() => console.log('连通性测试已完成'), () => console.log('连通性测试失败'))

测试页面元素的点击事件:

const webdriver = require('selenium-webdriver')
async function testBtnClick () {
    const driver = new webdriver.Builder().forBrowser(webdriver.Browser.CHROME).build()
    await driver.get(`https://www.baidu.com/`)
    const selector = '#form > span.bg.s_ipt_wr.quickdelete-wrap > span'
    const targetBtn = await driver.findElement(webdriver.By.css(selector))
    targetBtn.click()
}
testBtnClick().then(() => {})

centos 安装 chrome

1.vi /etc/yum.repos.d/google-chrome.repo

# Make sure you have below info in the file(remove hash).
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/x86_64
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub

2.yum install -y google-chrome-stable

常见问题

1.DevToolsActivePort file doesn’t exist

在创建 driver 时,添加 addArguments('no-sandbox')

你可能感兴趣的:(工具,自动化测试,selenium)