파일 업로드(File upload)

파일 업로드(File upload)

파일을 올리는 건 테스트에서 은근히 자주 마주치는 작업인데요, 문제는 Selenium이 파일 선택 대화상자(파일 업로드 다이얼로그)와는 직접 상호작용할 수 없다는 거예요. 그래서 Selenium은 대화상자를 열지 않고도 파일을 업로드할 수 있는 방법을 제공해요. 만약 대상 요소가 type 속성이 fileinput 요소라면, send keys 메서드로 업로드할 파일의 전체 경로를 전송하면 돼요. 파일 경로를 보내기만 하면 브라우저가 알아서 다이얼로그 없이 파일을 받아주는 방식이에요.

출처: 파일 업로드 - Selenium 공식 문서

본문

기본적인 흐름은 두 단계예요. 먼저 input[type=file] 요소를 찾고, 그 요소에 sendKeys로 업로드할 파일의 전체 경로를 보내요. 그런 다음 제출(submit) 버튼을 클릭하면 업로드가 완료돼요.

Java로 쓰면 이렇게 돼요.

WebElement fileInput = driver.findElement(By.cssSelector("input[type=file]"));
fileInput.sendKeys(uploadFile.getAbsolutePath());
driver.findElement(By.id("file-submit")).click();

Python에서는 이렇게 해요.

file_input = driver.find_element(By.CSS_SELECTOR, "input[type='file']")
file_input.send_keys(upload_file)
driver.find_element(By.ID, "file-submit").click()

C#에서는 이렇게 하죠.

IWebElement fileInput = driver.FindElement(By.CssSelector("input[type=file]"));
fileInput.SendKeys(uploadFile);
driver.FindElement(By.Id("file-submit")).Click();

Ruby는 이렇게 작성해요.

file_input = driver.find_element(css: 'input[type=file]')
file_input.send_keys(upload_file)
driver.find_element(id: 'file-submit').click

왜 이게 동작하는지가 핵심인데요. 파일 업로드 다이얼로그는 운영체제 수준의 창이라 브라우저 자동화 영역 밖이에요. 그래서 Selenium은 파일 경로를 input 요소에 직접 주입해서, 다이얼로그를 열지 않고도 브라우저가 그 파일을 선택한 것처럼 만들어요. 이때 중요한 건 파일의 전체 경로를 보내야 한다는 점이에요. 파일명만 보내면 상대 경로로 해석되어 원하는 파일을 못 찾을 수 있으니, 절대 경로를 사용해야 해요.

더 알아보기