今回はNode.jsでSeleniumを使用する際の基本操作をまとめたいと思います。
ある程度以下の操作を覚えておけばやりたいことは実現できるかと思います。
ページ遷移
await driver.get('遷移先URL')タグ名による要素特定
const element = await driver.findElement(By.tagName('p'))idによる要素特定
const element = await driver.findElement(By.id('hoge'))class名による要素特定
const element = await driver.findElement(By.className('fuga'))cssによる要素特定
const element = await driver.findElement(By.css('input[type="checkbox"]:checked'))複数要素の特定
const elements = await driver.findelements(By.className('piyo'))テキスト取得
const text = await element.getText()
const text = await element.getAttribute('innerHTML')検索文字の取得
const text = await element.getAttribute('value')要素の出現を待つ
await driver.wait(until.elementLocated(By.id('id')), 10000)要素の比較(一致)
assert.equal(text, 'aaa')要素の比較(不一致)
assert.notEqual(text, 'aaa')スクリーンショット
const base64 = await driver.takeScreenshot()
let buffer = Buffer.from(base64, 'base64')要素のクリック
await driver.findElement(By.id('hoge')).click()要素の数を取得
const length = await elements.length文字の入力
await driver.findElement(By.className('fuga')).sendKeys('aaaaa')入力のクリア
await driver.findElement(By.className('fuga')).clear()キーボード入力
await driver.findElement(By.className('fuga')).sendKeys(Key.DOWN, Key.Enter)hover
const action = driver.actions()
const element = await driver.findElement(By.id('hoge'))
await actions.move({origin: element}).perform()要素の中の要素を特定
const parentElement = await driver.findElement(By.className('fuga'))
const childElement = await parentElement.findElement(By.className('foo'))URL取得
const currentUrl = await driver.getCurrentUrl()ブラウザ戻る
await driver.navigate().back()ブラウザ進む
await driver.navigate().forward()リロード
await driver.navigate().refresh()ページタイトル取得
const title = await driver.getTitle()おわりに
実際に業務でseleniumを使用していて、上記を一通り押さえておくと困ることがなかったです。
テストは品質管理において重要ですが、全て手動でやると膨大な時間を要する可能性がありますが...
今後も自動化できる部分は自動化を進めていきたいと思います。