nodejs와 selenium-webdriver에서 element를 찾을 때 사용하는 selector에 대해 알아보겠습니다.
By Class를 이용하여 다양한 방법으로 원하는 element를 찾을 수 있습니다.
class, id, css selector, xpath, name 등을 지원합니다.


일반적으로 element ID가 사용가능하고, 고유하며, 예측가능하다면 검색할 때 element ID를 통해 하는 것이 매우 빠르고, 복잡하게 DOM을 이용하는 방법들을 속도에서 앞섭니다.
고유한 ID가 없다면, CSS selector이 그 다음으로 선호되는 방법입니다.
XPath 또한 CSS selector만큼 잘 작동되지만, 구문이 복잡하며 디버깅을 하기 힘들고 꽤 느린 경향이 있다고 합니다.


selenium element selector By nodejs

selenium selector By.id nodejs

element id를 이용하여 찾는 방법입니다.

const webdriver = require('selenium-webdriver'); const { By } = require('selenium-webdriver'); const chrome = require('selenium-webdriver/chrome'); const run = async () => { const service = new chrome.ServiceBuilder('./chromedriver').build(); chrome.setDefaultService(service); const driver = await new webdriver.Builder() .forBrowser('chrome') .build(); await driver.get('https://www.tistory.com/auth/login/old?redirectUrl=https%3A%2F%2Fwww.tistory.com%2F'); const loginInput = await driver.findElement(By.id('loginId')); await loginInput.sendKeys("userid"); const loginPw = await driver.findElement(By.id('loginPw')); await loginPw.sendKeys("password"); setTimeout(async () => { await driver.quit(); process.exit(0); }, 3000); } run();

By.id를 이용하여 element를 찾고 각각 값을 입력하였습니다.



selenium selector By.className nodejs

await driver.get('https://www.tistory.com/auth/login/old?redirectUrl=https%3A%2F%2Fwww.tistory.com%2F'); const chkLogin = await driver.findElement(By.className('img_top ico_check')); await chkLogin.click();

By.className를 이용하여 element를 찾고 로그인 상태 유지 버튼을 클릭하는 이벤트를 주었습니다.


selenium selector By.name nodejs

await driver.get('https://www.tistory.com/auth/login/old?redirectUrl=https%3A%2F%2Fwww.tistory.com%2F'); const loginInput = await driver.findElement(By.name('loginId')); await loginInput.sendKeys("userid"); const loginPw = await driver.findElement(By.name('password')); await loginPw.sendKeys("password");

By.name를 이용하여 element를 찾고 각각 값을 입력하였습니다.


selenium selector By.xpath nodejs

await driver.get('https://www.tistory.com/auth/login/old?redirectUrl=https%3A%2F%2Fwww.tistory.com%2F'); const loginInput = await driver.findElement(By.xpath('//*[@id="loginId"]')); await loginInput.sendKeys("userid"); const loginPw = await driver.findElement(By.xpath('//*[@id="loginPw"]')); await loginPw.sendKeys("password");

By.xpath를 이용하여 element를 찾고 각각 값을 입력하였습니다.

selenium에서 element를 찾을 때 사용하는 By 클래스에 대해 알아보았습니다.
By 클래스에서 제공하는 다양한 함수를 활용하면
element id, classname, name, css selector, xpath 등을 활용하여 원하는 element를 찾을 수 있습니다.
다음에는 원하는 페이지 로딩 혹은 element 로딩이 끝날때까지 기다리는 Wait에 대해 알아보겠습니다.


[Selenium-크롤링] - selenium 크롤링 nodejs - 브라우저 열기

[Selenium-크롤링] - selenium element 찾기 nodejs



'Selenium' 카테고리의 다른 글

selenium element timeout/wait By nodejs  (0) 2021.01.18
selenium WebElement python  (0) 2021.01.14
selenium python 페이지 열기  (0) 2021.01.13
selenium element 찾기 nodejs  (0) 2021.01.12
selenium 크롤링 nodejs - 브라우저 열기  (3) 2021.01.11

+ Recent posts