Node.js

selenium v4.0 (javascript)

blackbearwow 2024. 8. 9. 04:27

설치

npm install selenium-webdriver

import

const { Builder, Browser, By, Key, until } = require('selenium-webdriver');

 

1. 세션 시작하기

const driver = await new Builder().forBrowser(Browser.CHROME).build();

브라우저 종류: Browser.CHROME, Browser.EDGE, Browser.FIREFOX,  Browser.INTERNET_EXPLORER,  Browser.SAFARI

 

2. 브라우저에 액션 취하기

url 이동

await driver.get('https://www.selenium.dev');
//또는
await driver.navigate().to("https://www.selenium.dev/selenium/web/index.html");

뒤로 가기

await driver.navigate().back();

앞으로 가기

await driver.navigate().forward();

새로고침

await driver.navigate().refresh();

 

3. 브라우저 정보 요청하기

title 얻기

let title = await driver.getTitle();

현재 url 얻기

let currentUrl = await driver.getCurrentUrl();

 

4. 기다리는 전략 세우기

브라우저가 올바른 상태가 되기 전에 코드가 실행된다면 원하는 작업이 이루어지지 않을 것이다.

많은 사람은 sleep으로 작업을 기다리지만 충분하지 않은 시간으로 실패 가능성이 있다. 또한 충분한 시간을 설정한다면 작업이 너무 길어질것이다. 

 

암시적 기다림:

글로벌 세팅으로, 기본값은 0이다. element를 찾을 수 없다면 바로 error를 반환하지만, 값이 설정되어있다면 에러를 반환하기 전에 명시된 시간만큼 기다린다. 단위: ms

await driver.manage().setTimeouts({implicit: 500});

 

분명한 기다림:

구체적인 상태가 true가 될 때까지 기다린다.

let revealed = await driver.findElement(By.id("revealed"));

 

until을 사용해 title이 Google이 될때까지 10초간 대기

await driver.wait(until.titleIs('Google'), 10000);

 

5. element 찾기

class name으로 찾기

const loc = await driver.findElement(By.className('information'));

css selector로 찾기

const loc = await driver.findElement(By.css('#fname'));

id로 찾기

const loc = await driver.findElement(By.id('lname'));

name으로 찾기

const loc = await driver.findElement(By.name('newsletter'));

링크의 텍스트로 찾기

const loc = await driver.findElement(By.linkText('Selenium Official Page'));

링크의 텍스트의 부분으로 찾기

const loc = await driver.findElement(By.partialLinkText('Official Page'));

tag name으로 찾기

const loc = await driver.findElement(By.tagName('a'));

xpath로 찾기

const loc = await driver.findElement(By.xpath('//input[@value='f']'));

 

전체 DOM에서 찾기

const vegetable = await driver.findElement(By.className('tomatoes'));

DOM의 부분집합에서 찾기

const fruits = await driver.findElement(By.id('fruits'));
const fruit = fruits.findElement(By.className('tomatoes'));

찾기 최적화: 부분집합에서 찾기는 명령을 여러번 이행해야 한다. 그치만 css selector나 xpath를 사용해 한번에 원하는 요소를 찾을 수 있다.

const fruit = await driver.findElement(By.css('#fruits .tomatoes'));

 

모든 요소 찾기

하나의 요소가 아닌 여러 요소를 찾고싶을 때 사용한다.

const plants = await driver.findElements(By.tagName('li'));

 

focus된 요소 찾기

let focusAttr = await driver.switchTo().activeElement();

 

6. element에서 행동 취하기

클릭하기

await submitButton.click();

키보드 입력 보내기

await inputField.sendKeys('Selenium');

요소의 콘텐트를 클리어

await inputField.clear();

 

7. element정보 요청

화면에 display되었으면 true 아니면 false

let result =  await driver.findElement(By.name("email_input")).isDisplayed();

enable이면 true 아니면 false

let element =  await driver.findElement(By.name("button_input")).isEnabled();

선택되었으면 true 아니면 false

체크박스, 라디오버튼, input 요소 등등에 사용된다.

let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();

tagName 반환

let value = await driver.findElement(By.name('email_input')).getTagName();

사이즈와 포지션 얻기

let object = await driver.findElement(By.name('range_input')).getRect();

css값 얻기

let value = await driver.findElement(By.id('namedColor')).getCssValue('background-color');

텍스트 반환

let value = await message.getText();

attribute 데이터 얻기

// identify the email text box
const emailElement = await driver.findElement(By.xpath('//input[@name="email_input"]'));
    
//fetch the attribute "name" associated with the textbox
const nameAttribute = await emailElement.getAttribute("name");

//외부 HTML얻기
const outerHTML = await emailElement.getAttribute("outerHTML");

//내부 HTML얻기
const innerHTML = await emailElement.getAttribute("innerHTML");

 

8. 세션 끝내기

await driver.quit();

 

예제

(async function openNaver() {
    let driver = await new Builder().forBrowser(Browser.CHROME).build();
    try {
        await driver.get('https://www.naver.com/');
        let shortcut_items = await driver.findElements(By.className('shortcut_item'));
        for (let item of shortcut_items) {
            console.log(await item.getText());
        }
    } finally {
        await driver.quit();
    }
})();

 

참고: https://www.selenium.dev/documentation/webdriver/

-