Selenium 자동화 테스트에서 링크를 클릭하는 방법은 크게 두 가지가 있습니다. 바로 WebDriver의 click() 메서드를 사용하는 방법과 JavaScript Executor를 활용하는 방법입니다. 이 글에서는 두 방식의 차이점과 실제 구현 코드를 통해 각각의 사용법을 자세히 살펴보겠습니다.
1. WebDriver click()으로 링크 클릭하기
Selenium WebDriver에서 링크를 클릭하려면 linkText 또는 partialLinkText 로케이터를 사용할 수 있습니다. 각각 driver.findElement(By.linkText()) 메서드와 driver.findElement(By.partialLinkText()) 메서드를 호출하여 요소를 찾은 후 클릭 작업을 수행합니다.
HTML 문서에서 링크는 앵커 태그(<a>)로 감싸져 있습니다. 앵커 태그 내부에 포함된 전체 링크 텍스트는 driver.findElement(By.linkText(<링크 텍스트>)) 메서드의 인자로 전달되고, 부분적으로 일치하는 링크 텍스트는 driver.findElement(By.partialLinkText(<부분 링크 텍스트>)) 메서드의 인자로 전달됩니다. 마지막으로 click() 메서드를 호출하여 해당 링크를 클릭합니다.
다음은 앵커 태그로 구성된 링크의 HTML 코드 예시입니다.

코드 구현 예제
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
public class DriverClick{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// linkText 로케이터로 링크 식별
driver.findElement(By.linkText("Write for us")).click();
System.out.println("클릭 후 페이지 제목: " + driver.getTitle());
}
}2. JavaScript Executor로 링크 클릭하기
Selenium에서는 JavaScript Executor를 통해서도 링크 클릭과 같은 웹 동작을 수행할 수 있습니다. executeScript 메서드를 사용하며, 인자로 arguments[0].click() 스크립트와 클릭할 WebElement 객체를 함께 전달합니다.
이 방식은 일반적인 WebDriver 클릭이 동작하지 않는 경우, 예를 들어 요소가 화면 밖에 있거나 다른 요소에 가려진 상황에서도 클릭이 가능하다는 장점이 있습니다.
JavaScript Executor를 활용한 코드 구현 예제
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.By;
public class DriverClickJs{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// 링크 식별
WebElement l = driver.findElement(By.linkText("Write for us"));
// JavaScript Executor로 링크 클릭
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click();", l);
System.out.println("클릭 후 페이지 제목: " + driver.getTitle());
}
}실행 결과
두 코드 모두 실행하면 "Write for us" 링크가 성공적으로 클릭되고, 콘솔에는 클릭 후 이동한 페이지의 제목이 출력됩니다.

정리
일반적인 상황에서는 WebDriver의 click() 메서드를 사용하는 것이 권장됩니다. 실제 사용자의 동작과 가장 유사하게 시뮬레이션하기 때문입니다. 반면 요소가 가려지거나 클릭 이벤트가 차단되는 등 특수한 상황에서는 JavaScript Executor의 executeScript("arguments[0].click();", element) 방식이 효과적인 대안이 될 수 있습니다.