본문으로 바로가기
반응형

셀레니움(selenium)을 이용하여

korail 예매하기


크롬브라우저를 활용하였으며,

F12 를 통하여 element를 확인



import java.util.List;


import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.Select;

import org.openqa.selenium.support.ui.WebDriverWait;


public class KorailTest {

static ChromeDriver driver = new ChromeDriver();


public static void main(String[] args) {

String url = "http://www.letskorail.com";

driver.get(url);

setInputElement("input#txtGoStart", "부산"); //method 활용

setInputElement("input#txtGoEnd", "대전"); //method 활용

//startday

selectOption("select#time", "22"); //method 활용

WebElement searchBtn = driver.findElement(By.cssSelector("img[alt*=승차권예매"));  //버튼클릭

searchBtn.click();

WebDriverWait wait = new WebDriverWait(driver,20); //기다리기

WebElement aboutMe;

aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("img[name*=btnRsv2_1]")));

WebElement reserveBtn = driver.findElement(By.cssSelector("img[name*=btnRsv2_1]")); //버튼클릭

reserveBtn.click();

try {

//팝업창 닫기

        WebDriverWait wait1 = new WebDriverWait(driver, 1);

        wait1.until(ExpectedConditions.alertIsPresent());

        Alert alert = driver.switchTo().alert();

        alert.accept();

    } catch (Exception e) {

        //exception handling

    }

setInputElement("input#txtMember", "1234567890");

}

public static void selectOption(String selector, String value) {


WebElement select = 

driver.findElement(By.cssSelector("select#time"));

Select dropDown = new Select(select);           

List<WebElement> Options = dropDown.getOptions();

for(WebElement option:Options){

    if(option.getAttribute("value").equals(value)) {

      option.click(); //select option here;       

    }               

}

}

public static void setInputElement(String selector, String value) {

// String startCity = "부산";

WebElement startCityEle = driver.findElement(By.cssSelector(selector));

startCityEle.clear();

startCityEle.sendKeys(value);

}

}



반응형