Selenium3.X 与 Javascript (Nodejs)

传送门

# 官网网站
http://docs.seleniumhq.org/download/

# API DOC
http://goo.gl/hohAut

# 慕课网教程
http://www.imooc.com/learn/792

# 虫师教程
http://www.cnblogs.com/fnng/p/5854875.html

# 火狐浏览器历史版本下载
http://ftp.mozilla.org/pub/firefox/releases

# 火狐插件:firepath 非前端人员可能不熟悉css选择器,所以可以使用xpath
https://addons.mozilla.org/zh-CN/firefox/addon/firepath/?src=search

# 火狐插件:Selenium IDE 录制
https://addons.mozilla.org/zh-CN/firefox/addon/selenium-ide/?src=search

下载

npm install selenium-webdriver

各大浏览器厂商的官方驱动文件

browsercomponent
Chrome chromedriver(.exe)
Internet Explorer IEDriverServer.exe
Edge MicrosoftWebDriver.msi
Firefox 47+ geckodriver(.exe)
PhantomJS phantomjs(.exe)
Opera operadriver(.exe)
Safari safaridriver

PS: driver的版本 与 浏览器的版本密切相关,请按需下载,比如chromedriver可以通过其中notes.txt查看支持的版本信息

然后,把这些驱动下载,并存放到一个目录中,例如:D:/driver/ ,再把这个目录添加到系统环境变量PATH下面。

下面我以Firefox为例,既然上面写着47+ , 那么我就下载48来演示好了

Firefox历史版本下载:http://ftp.mozilla.org/pub/firefox/releases/

官方demo代码

var webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until;

var driver = new webdriver.Builder()
    .forBrowser('firefox')
    .build();

driver.get('http://www.google.com/ncr');
driver.findElement(By.name('q')).sendKeys('webdriver');
driver.findElement(By.name('btnG')).click();
driver.wait(until.titleIs('webdriver - Google Search'), 2000);
driver.quit();

PS:如果出现【Could not convert 'text' to string】,别担心,这是新版webdriver的bug。在stackoverflow上已有其它开发者解决:

https://github.com/mozilla/geckodriver/issues/683

只需要修改node_modulesselenium-webdriverlibwebdriver.js中的代码即可:

https://github.com/SeleniumHQ/selenium/commit/6907a129a3c02fe2dfc54700137e7f9aa025218a

正常运行后,会自动启动Firefox,访问 Google 并且搜索 webdriver。然后关闭浏览器。

有时候,需要模拟移动端浏览器测试。例子如下,这次使用Chrome浏览器来测试,请下载对应的版本驱动

var webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until,
    chrome = require('selenium-webdriver/chrome');

var driver = new webdriver.Builder()
    .forBrowser('chrome')
    .setChromeOptions(new chrome.Options()
        .setMobileEmulation({deviceName: 'Google Nexus 5'}))
    .build();

driver.get('https://m.baidu.com');
driver.findElement(By.name('word')).sendKeys('webdriver');
driver.findElement(By.name('word')).submit();
driver.wait(until.titleIs('webdriver - 百度'), 2000);
driver.quit();

 常用的deviceName还是以iPhone为主,名字举例:Apple iPhone 6 Plus、Apple iPhone 4等

原文地址:https://www.cnblogs.com/CyLee/p/6963858.html