Selenium Webdriverを使うのにwd.jsを使っているのですが、node.jsだとどうやってselect boxを選択するのか分からなくて調べたので結果をメモしておきます。
Javaだとelementに対してselectByVisibleText()を使うことで選択可能みたいだったんだけど、wd.jsのAPIマニュアルを見るとそんなのも無いし・・・という感じで調べていたらURLは忘れましたがstackoverflowでpythonの場合のやり方を聞いている人がいて、回答にxpathを指定すればOKというのを見つけて、なるほどね!ということでwd.jsでもやってみたところ上手くできました。
下はyahooの路線検索で、22日の13時20分着の電車を調べるサンプルコードです。
"use strict";
var wd = require("wd");
require('colors');
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var should = chai.should();
chaiAsPromised.transferPromiseness = wd.transferPromiseness;
describe("Select box test", function () {
this.timeout(300000);
var driver;
before(function () {
var serverConfig = {
host: 'localhost',
port: 4444
};
driver = wd.promiseChainRemote(serverConfig);
var desired = {
browserName: 'chrome',
platformName: 'mac',
};
return driver.init(desired);
});
after(function () {
return driver
.quit();
});
it("should get the url", function () {
return driver
.get('http://www.yahoo.co.jp')
.waitForElementByLinkText('路線')
.click()
.waitForElementByCssSelector('#sfrom')
.type('秋葉原')
.waitForElementByCssSelector('#sto')
.type('新宿')
.waitForElementByXPath('//*[@id="d"]/option[22]')
.click()
.waitForElementByXPath('//*[@id="hh"]/option[13]')
.click()
.waitForElementByXPath('//*[@id="mm"]/option[20]')
.click()
.waitForElementByXPath('//*[@id="tsArr"]')
.click()
.waitForElementById('searchModuleSubmit')
.click()
.waitForElementByClassName('title')
.text().should.eventually.equal('秋葉原→新宿')
.saveScreenshot('test_result.png');
});
});
実行結果はこのように。