본문 바로가기

테스트툴/Selenium

Selenium Webdriver 모든 링크와 연결할 수 없는 링크 찾기

일부 서버 오류로 인해 다운되었거나 작동하지 않을 수 있는 링크가 있을 수도 있습니다

URL은 항상 유효한 2xx 상태를 갖습니다

그 외에도 HTTP 상태 코드로, 잘못된 요청의 경우 4xx 및 5xx 상태를 갖습니다

이러한 상태일 때 링크를 직접 클릭하여 확인할 때까지 링크가 작동하는지 여부를 확인할 수 없습니다

 

사용자가 오류 페이지로 이동하면 안되기 때문에 끊어진 링크가 없는지 항상 확인하도록 해야 합니다.

규칙이 올바르게 업데이트되지 않았거나 요청된 리소스가 서버에 없는 경우 오류가 발생합니다

각 웹 페이지에는 많은 수의 링크가 있을 수 있으며 모든 페이지에 대해 수동 프로세스를 반복해야 하기 때문에 직접 수동으로 확인하기는 다소 어려움이 있습니다

그러므로 프로세스를 자동화하는 Selenium을 사용하는 자동화 스크립트가 더 적절한 방법입니다

 

끊어진 링크 및 이미지 확인하기

실습은

 

Information Management, Compliance, and Analytics Solutions - ZL Tech

A unified information management platform to get more from your data: eDiscovery, compliance, privacy, records management, and analytics.

www.zlti.com

위 페이지를 활용합니다

 

우선 <a> 태그를 기반으로 웹 페이지의 모든 링크를 수집합니다

링크에 대한 HTTP 요청을 보내고 HTTP 응답 코드를 읽습니다

그리고 HTTP 응답 코드를 기반으로 링크가 유효한지, 끊어졌는지 확인합니다

모든 링크에 대해 이 작업을 반복하면 됩니다

package newpackage;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.*;

public class MyClass {
	private static WebDriver driver = null;
	
	public static void main(String[] args) {
		System.setProperty("webdriver.chrome.driver", "c:/selenium/chromedriver.exe");
		WebDriver driver = new ChromeDriver();
		
		String getURL = "https://www.zlti.com/";
		String url = "";
		HttpURLConnection huc = null;
		int respCode = 200;
		
		driver.manage().window().maximize();
		driver.get(getURL);
		
		List<WebElement> links = driver.findElements(By.tagName("a"));
		Iterator<WebElement> it = links.iterator();
		
		while(it.hasNext()){
			url = it.next().getAttribute("href");
			System.out.println(url);
			
			if(url == null || url.isEmpty()){
				System.out.println("URL is either not configured for anchor tag or it is empty");
				continue;
			}
			if(!url.startsWith(getURL)){
				System.out.println("URL belongs to another domain, skipping it.");
				continue;
			}
			try{
				huc = (HttpURLConnection)(new URL(url).openConnection());
				huc.setRequestMethod("HEAD");
				huc.connect();
				respCode = huc.getResponseCode();
				
				if(respCode>=400){
					System.out.println(url + "is a broken link");
				}
				else{
					System.out.println(url + "is a valid link");
				}				
			}
			catch(MalformedURLException e){
				e.printStackTrace();
			}
			catch(IOException e){
				e.printStackTrace();
			}
		}
		driver.quit();
	}
}

위 코드의 결과로

Console 결과

Console 창에 결과가 출력됩니다

 

소스 설명

import java.net.HttpURLConnection;

위 패키지의 메서드를 사용하여 HTTP 요청을 보내고 응답에서 HTTP 응답 코드를 캡처합니다

List<WebElement> links = driver.findElements(By.tagName("a"));

<a> 태그를 가지는 부분을 모두 찾아 웹 페이지의 모든 링크를 식별하고 목록에 저장합니다

Iterator<WebElement> it = links.iterator();

목록을 순회할 반복자를 확보합니다

url = it.next().getAttribute("href");

<a> 태그의 href를 찾아 URL을 변수에 저장합니다

if(url == null || url.isEmpty()){
	System.out.println("URL is either not configured for anchor tag or it is empty");
	continue;
}

URL이 null인지 비어 있는지 확인합니다

if(!url.startsWith(getURL)){
	System.out.println("URL belongs to another domain, skipping it.");
	continue;
}

URL이 타사 도메인에 속하는 경우에 뛰어넘습니다

startsWith 메서드는 문자열이 지정된 접두사로 시작하는지 테스트합니다. 즉, 얻은 URL의 앞부분이 실습하고 있는 홈페이지인 http://www.zlti.com로 시작하는지 확인하는 코드입니다

huc = (HttpURLConnection)(new URL(url).openConnection());

HttpURLConnection 클래스에는 HTTP 요청을 보내고 HTTP 응답을 캡처하는 메서드가 있습니다. 따라서 openConnection() 메서드의 출력은 HttpURLConnection으로 형 변환됩니다

huc.setRequestMethod("HEAD");

요청 유형을 HEAD로 설정하여 문서 본문이 아닌 헤더만 반환하도록 합니다

respCode = huc.getResponseCode();

getResponseCode() 메서드를 사용하여 요청에 대한 응답 코드를 얻습니다

if(respCode>=400){
	System.out.println(url + "is a broken link");
}
else{
	System.out.println(url + "is a valid link");
}

응답 코드를 이용하여 링크 상태를 확인합니다


웹 페이지의 모든 링크 얻기

웹 테스트의 일반적인 절차 중 페이지에 있는 모든 링크가 작동하는지 테스트하는 것입니다

이 작업은 for-each 루프와 findElement(), By.tagName() 메서드를 활용하면 편하게 할 수 있습니다

실습은

 

Welcome: Mercury Tours

Atlanta to Las Vegas $398 Boston to San Francisco $513 Los Angeles to Chicago $168 New York to Chicago $198 Phoenix to San Francisco $213    

demo.guru99.com

위 페이지를 활용할 것입니다

노란 부분만 활용할 것이기 때문에

XPath를 활용하여 요소에 접근한 뒤에 링크들을 찾아갈 것입니다

package newpackage;

import org.openqa.selenium.chrome.ChromeDriver;

import java.util.List;		
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.*;

public class MyClass {
	public static void main(String[] args) {
		System.setProperty("webdriver.chrome.driver", "c:/selenium/chromedriver.exe");
		WebDriver driver = new ChromeDriver();
		
		String getURL = "http://demo.guru99.com/test/newtours/";
		//driver.get(getURL);
		
		String underConsTitle = "Under Construction: Mercury Tours";
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
		
		driver.get(getURL);//
		
		WebElement getTable = driver.findElement(By.xpath("/html/body/div[2]"));
		List<WebElement> linkElements = getTable.findElements(By.tagName("a"));							
	    String[] linkTexts = new String[linkElements.size()];							
	    int	i = 0;
		
		for(WebElement e : linkElements){
			linkTexts[i] = e.getText();
			i++;
		}
		for(String t : linkTexts){
			driver.findElement(By.linkText(t)).click();
			if(driver.getTitle().equals(underConsTitle)){
				System.out.println("\"" + t + "\"" + " is under construction.");
			}
			else{
				System.out.println("\"" + t + "\"" + " is working.");
			}
			driver.navigate().back();
		}
		driver.quit();
	}
}

위 코드의 결과로

Console 결과

Console 창에 위와 같은 결과가 출력됨을 확인할 수 있습니다

'테스트툴 > Selenium' 카테고리의 다른 글

Selenium Webdriver 툴 팁  (0) 2021.04.03
Selenium 웹 테이블  (0) 2021.03.28
Selenium 경고, 팝업 창 처리하기  (0) 2021.03.21
Selenium 파일 업로드  (0) 2021.03.20
Selenium 마우스 이벤트와 키보드 이벤트  (0) 2021.03.19