【node.js】seleniumの要素の特定方法一覧

【node.js】seleniumの要素の特定方法一覧

seleniumでコーディング時、要素の特定の時のお作法などよく忘れるので、備忘録です。

要素の特定方法

Xpath

js
await driver.findElements(By.xpath('//*[@id="Result"]/div[2]/p/span'))

クラス名

js
await driver.findElements(By.className('class'));

2つ以上のクラス名

js
await driver.findElements(By.css('.class1.class2'));await driver.findElements(By.css('.class1.class2.class3'));

タグ名

js
await element.findElement(By.tagName('a'));await element.findElement(By.tagName('h1'));

クラス名の中のaタグ

js
await driver.findElements(By.css('.ClassName > a'));

ボタンをクリックする

js
await driver.findElements(By.xpath('')).click();

戻り値をボタンにして、後ほどクリックする

js
const button = await driver.wait(until.elementLocated(By.className('class')), 5000);await button.click();

テキストを取得する

.entry_title というclass名のタイトルを取得したい場合

js
let titleElement = await driver.wait(until.elementLocated(By.className('entry_title')), 5000);let titleText = await titleElement.getText();

スプレッドシートで使えるスクレイピング

スプレッドシートでURLからタイトルタグを取得する

other
=IMPORTXML(,"//title")

 

あなたへのおすすめ