Chrome에서 Selenium WebDriver 테스트 사례를 실행하는 방법은 무엇입니까?


160

나는 이것을 시도했다

WebDriver driver = new ChromeDriver();

하지만 오류가 발생합니다.

실패한 테스트 : setUp (com.TEST) : 드라이버 실행 파일의 경로는 webdriver.chrome.driver 시스템 속성으로 설정해야합니다. 자세한 내용은 여기 코드를 참조 하십시오 . 최신 버전은 링크 에서 다운로드 할 수 있습니다

Chrome에서 Selenium-WebDriver 테스트 사례를 테스트하려면 어떻게해야합니까?


code.google.com/p/chromedriver/downloads/list 에서 셀레늄 크롬 드라이버를 다운로드하여 "외부 항아리 추가"아래의 일람표 라이브러리에 추가 했는지 여부를 알 수 있다면 도움이 될 것입니다. 암호.
— Hemanth December

답변:


252

ChromeDriver 다운로드 에서 실행 가능 드라이버를 다운로드해야합니다.

그런 다음 드라이버 오브젝트를 작성하기 전에 다음을 사용하면됩니다 (이미 올바른 순서로 표시됨).

System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();

ChromeDriver 설명서의 가장 유용한 안내서에서 발췌 한 것 입니다.


@aimbire : 야, 나는 같은 문제에 직면하고있다. 나는 당신이 제안한 것과 똑같은 일을했지만이 오류가 발생했습니다. "java.lang.IllegalStateException : 드라이버 실행 파일이 존재하지 않습니다 : D : \ selenimPRJarg1 \ chromedriver.exe"무엇인가 빠졌습니다 "?
— kTiwari

여기 docs.seleniumhq.org/download 에서 Selenium Standalone Server를 다운로드 하고 jar 파일을 Java 프로젝트에 대한 종속성으로 추가해야합니다.
— dikirill

4
어디에서 이것을 사용하거나 타이핑합니까? System.setProperty ( "webdriver.chrome.driver", "/ path / to / chromedriver"); WebDriver 드라이버 = 새로운 ChromeDriver ();
— tijnn

1
나는이 질문에 대한 모든 답을 탐구했고 이것 만이 나를 위해 일했다. (y)
— puffles

이것은 기술적으로 정확하지만 실제로 환경 변수를 코드로 설정해서는 안되며 코드의 경로를 하드 코딩하는 것과 같습니다. 환경 변수는 코드를 실행하는 컴퓨터에서 설정해야하므로 각 컴퓨터는 크롬 드라이버 실행 파일을 고유 한 위치에 저장할 수 있지만 모든 것이 여전히 작동합니다.
— Ardesco

21

Chrome 드라이버에서 Chrome 드라이버 의 업데이트 버전을 다운로드 하십시오. 릴리스 노트도 읽어보십시오 여기 에서 Chrome 브라우저가 업데이트 된 경우 새 브라우저 버전으로 압축 할 수 있으므로 위 링크에서 새 chormedriver를 다운로드해야합니다.

 public class chrome 
 {

  public static void main(String[] args) {

       System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
       WebDriver driver = new ChromeDriver();


    driver.get("http://www.google.com");

  }

 }

3
이제는 번거로운 솔루션입니다. 요즘 사용하는 경우 이것을 변경하는 것이 좋습니다.
— aimbire

1
다운로드 링크가 오래되었습니다.
— 코딩 사라지다

이 코드는 Chrome 버전 69.0.3497.100 (공식 빌드) (64 비트)에서 작동하지 않습니다. 새로운 코드를 제안하십시오. 지금까지이 이전 버전에서보다 65.0.0 버전 일하는
— Mitesh Thakery

18

폴더에 chromeDriver를 다운로드하고이 폴더를 PATH 변수에 추가해야합니다. 콘솔을 다시 시작해야 작동합니다.


8

MacOS에서 homebrew를 사용하는 경우 다음 명령을 사용할 수 있습니다.

(편집) :brew tap homebrew/cask && brew cask install chromedriver

다른 구성없이 그 후에 잘 작동합니다.


2
지금까지는입니다 brew tap homebrew/cask && brew cask install chromedriver.
— luk2302

6

크롬 드라이버를 설치해야합니다. 아래와 같이 너깃을 사용하여이 패키지를 설치할 수 있습니다


1
이것은 하나 일 수 있지만 NuGet의 버전이 너무 오래되었습니다 : 2.10.0 2014 년 10 월 13 일
— Tiago Freitas Leal

3 월 23 일에 구식이되었습니다. 최신 Chrome에서 사용할 수 없습니다.
— willem

6

아래 코드를 사용하여 Selenium 웹 드라이버를 사용하여 Chrome에서 테스트 사례를 실행할 수 있습니다.

import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ChromeTest {

    /**
     * @param args
     * @throws InterruptedException
     * @throws IOException 
     */
    public static void main(String[] args) throws InterruptedException, IOException {
        // Telling the system where to find the Chrome driver
        System.setProperty(
                "webdriver.chrome.driver",
                "E:/chromedriver_win32/chromedriver.exe");

        WebDriver webDriver = new ChromeDriver();

        // Open google.com
        webDriver.navigate().to("http://www.google.com");

        String html = webDriver.getPageSource();

        // Printing result here.
        System.out.println(html);

        webDriver.close();
        webDriver.quit();
    }
}

5

chromedriver 여기 에서 최신 버전을 찾으 십시오 . 일단 다운로드되면 파이썬 설치 루트에서 압축을 풉니 다 (예 :) C:/Program Files/Python-3.5. 어디에서나 경로를 지정하거나 경로 등에 추가 chromedriver할 필요가 없습니다 . 방금 깨끗한 Python 설치에서 수행했으며 작동합니다.


4
나쁜 조언 ... 파이썬 설치를 오염시키지 마십시오
— Corey Goldberg

또한 영업 이익은 결코 파이썬을 지정하지
— 코리 골드버그

4

최신 버전의 크롬 드라이버를 다운로드하고 다음 코드를 사용하십시오.

System.setProperty("webdriver.chrome.driver", " path of chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.manage().window().maximize();
Thread.sleep(10000);
driver.get("http://stackoverflow.com");

1

우분투에서는 간단하게 chromium-chromedriver패키지 를 설치할 수 있습니다 :

apt install chromium-chromedriver

오래된 셀레늄 버전도 설치됩니다. 최신 셀레늄을 설치하려면

pip install selenium

0

위의 모든 대답은 정확합니다. 다음은 문제와 해결책에 대한 약간의 잠수입니다.

예를 들어 셀레늄의 드라이버 생성자

WebDriver driver = new ChromeDriver();

드라이버 실행 파일을 검색합니다 (이 경우 크롬 드라이버는 서비스가 예외를 던진 실행 파일을 찾을 수없는 경우에 크롬 드라이버 실행 파일을 검색합니다)

여기에서 예외가 발생합니다 (체크 상태 방법 참고).

 /**
   *
   * @param exeName Name of the executable file to look for in PATH
   * @param exeProperty Name of a system property that specifies the path to the executable file
   * @param exeDocs The link to the driver documentation page
   * @param exeDownload The link to the driver download page
   *
   * @return The driver executable as a {@link File} object
   * @throws IllegalStateException If the executable not found or cannot be executed
   */
  protected static File findExecutable(
      String exeName,
      String exeProperty,
      String exeDocs,
      String exeDownload) {
    String defaultPath = new ExecutableFinder().find(exeName);
    String exePath = System.getProperty(exeProperty, defaultPath);
    checkState(exePath != null,
        "The path to the driver executable must be set by the %s system property;"
            + " for more information, see %s. "
            + "The latest version can be downloaded from %s",
            exeProperty, exeDocs, exeDownload);

    File exe = new File(exePath);
    checkExecutable(exe);
    return exe;
  }

다음은 예외를 발생시키는 점검 상태 메소드입니다.

  /**
   * Ensures the truth of an expression involving the state of the calling instance, but not
   * involving any parameters to the calling method.
   *
   * <p>See {@link #checkState(boolean, String, Object...)} for details.
   */
  public static void checkState(
      boolean b,
      @Nullable String errorMessageTemplate,
      @Nullable Object p1,
      @Nullable Object p2,
      @Nullable Object p3) {
    if (!b) {
      throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3));
    }
  }

해결책 : 드라이버 객체를 생성하기 전에 다음과 같이 시스템 속성을 설정하십시오

System.setProperty("webdriver.gecko.driver", "path/to/chromedriver.exe");
WebDriver driver = new ChromeDriver();

다음은 드라이버 서비스가 드라이버 실행 파일을 검색하는 코드 스 니펫 (chrome 및 firefox)입니다.

크롬:

   @Override
    protected File findDefaultExecutable() {
      return findExecutable("chromedriver", CHROME_DRIVER_EXE_PROPERTY,
          "https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver",
          "http://chromedriver.storage.googleapis.com/index.html");
    }

파이어 폭스 :

@Override
 protected File findDefaultExecutable() {
      return findExecutable(
        "geckodriver", GECKO_DRIVER_EXE_PROPERTY,
        "https://github.com/mozilla/geckodriver",
        "https://github.com/mozilla/geckodriver/releases");
    }

여기서 CHROME_DRIVER_EXE_PROPERTY = "webdriver.chrome.driver"및 GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver"

다른 브라우저의 경우도 마찬가지입니다. 다음은 사용 가능한 브라우저 구현 목록의 스냅 샷입니다.

여기에 이미지 설명을 입력하십시오


0
To run Selenium WebDriver test cases in Chrome, follow these steps:


first of all set the property & chrome driver path

System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
then initialize the Chrome Driver's object

WebDriver driver = new ChromeDriver();
then pass the url into get method of WebDriver

driver.get("http://www.google.com");

0

바이너리를 프로젝트 리소스 디코 리에 포함 시켰습니다.

src\main\resources\chrome\chromedriver_win32.zip
src\main\resources\chrome\chromedriver_mac64.zip
src\main\resources\chrome\chromedriver_linux64.zip

암호:

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.*;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public WebDriver getWebDriver() throws IOException {
    File tempDir = Files.createTempDirectory("chromedriver").toFile();
    tempDir.deleteOnExit();
    File chromeDriverExecutable;

    final String zipResource;
    if (SystemUtils.IS_OS_WINDOWS) {
        zipResource = "chromedriver_win32.zip";
    } else if (SystemUtils.IS_OS_LINUX) {
        zipResource = "chromedriver_linux64.zip";
    } else if (SystemUtils.IS_OS_MAC) {
        zipResource = "chrome/chromedriver_mac64.zip";
    } else {
        throw new RuntimeException("Unsuppoerted OS");
    }

    try (InputStream is = getClass().getResourceAsStream("/chrome/" + zipResource)) {
        try (ZipInputStream zis = new ZipInputStream(is)) {
            ZipEntry entry;
            entry = zis.getNextEntry();
            chromeDriverExecutable = new File(tempDir, entry.getName());
            chromeDriverExecutable.deleteOnExit();
            try (OutputStream out = new FileOutputStream(chromeDriverExecutable)) {
                IOUtils.copy(zis, out);
            }
        }
    }

    System.setProperty("webdriver.chrome.driver", chromeDriverExecutable.getAbsolutePath());
    return new ChromeDriver();
}

-2

chromedriver의 exe를 다운로드하여 현재 프로젝트 위치에 추출하십시오. 여기에서 최신 버전의 chromedriver를 다운로드 할 수있는 링크가 있습니다.

https://sites.google.com/a/chromium.org/chromedriver/

시작 브라우저의 간단한 코드와 url로 이동하십시오.

System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");

WebDriver driver = new ChromeDriver();

driver.get("https://any_url.com");

크롬 드라이버를 다운로드하고 압축을 풉니 다. 그런 다음 프로젝트에서 폴더를 만들고 chromedriver로 이름을 지정하고 .exe 파일을 그 안에 보관하십시오. 이 경로를 사용하십시오. 간단한 코드 예입니다. 'code'System.setProperty ( "webdriver.chrome.driver", System.getProperty ( "user.dir") + "\\ chromedriver \\ chromedriver.exe"); WebDriver 드라이버 = 새로운 ChromeDriver (); driver.get ( " google.co.in" ); WebElement 검색 창 = driver.findElement (By.name ( "q")); searchbox.sendKeys ( "최고의 셀레늄 비디오 튜토리얼"); searchbox.submit ();
— vinay

의견이 추가 된 정보로이 답변을 업데이트하는 것을 고려하십시오.
— Ricardo Souza
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.