사용자 도구

사이트 도구


wiki:java:selenium

Selenium 사용방법

  • description :
  • author : 도봉산핵주먹
  • email : hylee@repia.com
  • lastupdate : 2020-11-11

Selenium이란?

Selenium은 브라우져의 API를 이용하여 웹 화면 테스팅을 하기 위한 모듈입니다.
Selenium은 무료 오픈 소스입니다.
Selenium은 브라우저를 원격 제어하는 함으로 웹 서비스의 브라우저의 호환 테스팅, 자동화 테스팅에 적합한 모듈입니다.
웹 크롤링으로 사용하기에는 성능 및 환경의 제약으로 적합하지 않습니다.

지원하는 브라우져
  • firefox
  • Chrome
  • safari
  • IE
  • 등등
Tip

다만 각 브라우져에 Drive가 있어야 실행 가능합니다.


Chrome Driver Download


현재 크롬버전 확인



위 사진같이 클릭하면 아래와 같은 화면이 나옵니다
크롬 버전을 확인하면 됩니다.


확인 후 아래 페이지로 이동하여 같은 버전의 driver를 다운로드 받으면 됩니다.
Chrome 웹 드라이브 다운로드 페이지



maven

<dependency>
   <groupId>org.seleniumhq.selenium</groupId>
   <artifactId>selenium-java</artifactId>
   <version>2.35.0</version>
</dependency>

Selenium code

java

 
 
package main;
 
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class SeleniumTest
{
 
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		chromTest();
 
	}
 
	public static void chromTest() throws IllegalStateException
	{
		WebDriver driver = null;
		try
		{
			// drvier 설정 -
			System.setProperty("webdriver.chrome.driver", "D:\\eclipse_repository\\eGovFrameDev-3.9.0-64bit\\workspace\\parsingApi\\util\\chromedriver.exe");
			// Chrome 드라이버 인스턴스 설정
			driver = new ChromeDriver();
 
			// 접속하고 싶은 URL
			// 아래 URL은 구글번역입니다.
			driver.get(
					"https://www.google.com/search?q=%EA%B5%AC%EA%B8%80%EB%B2%88%EC%97%AD&oq=%EA%B5%AC%EA%B8%80%EB%B2%88%EC%97%AD&aqs=chrome..69i57j35i39j0l4.2179j0j7&sourceid=chrome&ie=UTF-8");
			// 대기 설정
			driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
			// xpath 패턴의 값 selector.
			WebElement element;
 
			// test를 위한 배열
			String[] s_array = new String[3];
			s_array[0] = "This book aims to strengthen an understanding of the sculptural possibilities of form and space through developing a visual language and structure that recognizes and ";
			s_array[1] = "gives priority to 3dimensional visual perception It is written so as to apply to both the active process of shaping 3D form and space and analyzing any existing visual situation Introduction";
			s_array[2] = "收費服務,可用於單詞,詞組和";
 
			// *[@id="tw-sl"]/span[1]
 
			// 배열 반복문
			for (String str : s_array)
			{
				// 언어선택하는 버튼
				element = driver.findElement(By.xpath("//*[@id='tw-sl']/span[1]"));
				// 언어선택하는 버튼 클릭
				element.click();
 
				Thread.sleep(1000);
 
				// 언어감지 버튼 선택
				element = driver.findElement(By.xpath(
						"//*[@id='tw-container']/g-expandable-container/div/div/div[6]/g-expandable-container/div/g-expandable-content/span/div/div[3]/div[1]/div/div[1]/div[2]"));
				// 언어감지 버튼 클릭
				element.click();
				// 번역 할 input창 선택
				element = driver.findElement(By.xpath("//*[@id='tw-source-text-ta']"));
				// 번역 할 input창에 문장 넣기
				element.sendKeys(str);
				// 대기 설정
				Thread.sleep(1000);
				// css 패턴의 값 selector.
				WebElement elementd = driver.findElement(By.cssSelector("#tw-target-text > span"));
 
				System.out.println("elementd : " + elementd.getText());
				// element 초기화
				element.clear();
			}
 
		} catch (Throwable e)
		{
			e.printStackTrace();
		} finally
		{
			driver.close();
 
			// test 용
			System.exit(0);
		}
 
//		
 
	}
 
}

consol

elementd : 이 책은 인식하고 인식하는 시각적 언어와 구조를 개발하여 형태와 공간의 조각 적 가능성에 대한 이해를 강화하는 것을 목표로합니다.
elementd : 3 차원 시각 인식을 우선시하며 3 차원 형태와 공간을 형성하는 능동적 인 과정과 기존의 시각 상황을 분석하는 과정 모두에 적용 할 수 있도록 작성되었습니다.
elementd : 단어, 구, 구에 사용할 수있는 유료 서비스
\\
\\

CentOS에 크롬설치

서버환경에 크롬을 설치해야 Selenium이 동작합니다.
크롬드라이버도 리눅스 버전을 받아야 합니다.

1. 크롬 repo 등록

$ vi /etc/yum.repos.d/google-chrome.repo
[google-chrome] 
name=google-chrome 
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch 
enabled=1 
gpgcheck=1 
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub 

2. 크롬 설치

$ yum install google-chrome-stable 


3. 크롬 버전 확인

$ google-chrome --version 


Tip

자바코드를 실행하면 크롬창이 뜨면서 번역하는 과정이 보여집니다.

Troubleshooting

Ref

/var/services/web/dokuwiki/data/pages/wiki/java/selenium.txt · 마지막으로 수정됨: 2023/01/13 18:44 (바깥 편집)