심심한잉여의 잡동사니

[JAVA/셀레니움]JAVA로 셀레니움 다루기 본문

코딩일기/Java

[JAVA/셀레니움]JAVA로 셀레니움 다루기

심심한잉여 2023. 8. 22. 11:36
반응형

셀레니움은 주로 갯글 봇, 자동 게시글 업로드 등 다양하게 활용이 되는 브라우저 자동화 프레임워크로 볼 수 있다.

다양한 곳에서 업무 자동화 또는 웹 매크로를 제작할 때 사용되며 주로 파이썬을 통해 사용을 하는 것 같다.

이를 한번 찍먹을 해봄으로써 추후 비슷한 기능이 필요할 때 사용해보려고 한다.


- 셀레니움 사용방법

JAVA와 크롬을 이용하여 만들어보도록 하자 

위 캡쳐본에서 나온것과 같이 크롬 브라우저 정보를 확인하고 해당 버전에 맞는 chrome WebDriver를 다운로드 받는다.

웹 드라이버 다운로드 링크 : https://chromedriver.chromium.org/downloads

 

ChromeDriver - WebDriver for Chrome - Downloads

Current Releases If you are using Chrome version 115 or newer, please consult the Chrome for Testing availability dashboard. This page provides convenient JSON endpoints for specific ChromeDriver version downloading. For older versions of Chrome, please se

chromedriver.chromium.org

위 링크에서 확인한 크롬 버전에 맞는 웹 드라이버를 다운로드 받는다.

셀레니움(라이브러리,jar) 다운로드 링크 : https://www.selenium.dev/downloads/

 

Downloads

Selenium automates browsers. That's it!

www.selenium.dev

웹 드라이버와 셀레니움 라이브러리를 다운로드 받았다면

이를 통해 네이버에 로그인하는 예제를 만들어보자.

 

먼저 준비된 준비물(웹드라이버, 셀레니움 라이브러리)을 가지고 프로젝트를 만든 후 라이브러리를 등록하고

아래의 예제 코드와 같이 작성한 후 실행하면 된다.

public class Test {

    public static void main(String[] args) throws IOException {

        Test test = new Test();
        test.crawl();
    }

    //WebDriver
    private WebDriver driver;
    private WebElement webElement;

    //Properties
    public static final String WEB_DRIVER_ID = "webdriver.chrome.driver";
    public static final String WEB_DRIVER_PATH = "C:\\dev\\selenium\\chromedriver_win32\\chromedriver.exe";

    //크롤링 할 URL
    private String base_url;


    public Test() throws IOException {
        super();

        //System Property SetUp
        System.setProperty(WEB_DRIVER_ID, WEB_DRIVER_PATH);
           
        ChromeOptions options = new ChromeOptions();
       
        options.addArguments("--start-maximized");
        options.addArguments("--disable-popup-blocking");
        driver = new ChromeDriver(options);
        base_url = "https://www.naver.com/";
    }

    public void crawl() {

        try {
            driver.get(base_url);

            webElement = driver.findElement(By.className("MyView-module__link_login___HpHMW"));
            webElement.click();

            webElement = driver.findElement(By.id("id"));
            webElement.sendKeys("아이디");
            webElement = driver.findElement(By.id("pw"));
            webElement.sendKeys("비밀번호");
            webElement = driver.findElement(By.id("log.login"));
            webElement.click();

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            driver.close();
        }

    }

}

 

위와 같이 코드를 작성하여 실행하면 

이런 모양으로 만들어 질 것이다.

정상적으로 아이디와 패스워드를 작성 후 클릭하게 만들었다면 봇 방지 시스템을 보게 되겠지만 예제이기 때문에 여기까지만 하는 것으로 하겠다.

필자는 이 기능들을 가지고 추후 웹을 통한 자동화가 필요한 경우 사용을 해보고자 한다.

반응형