평범한 이야기들

[Selenium] Headless 모드 사용으로 창 없이 크롤링 하기 본문

평범한 개발 이야기/ETC

[Selenium] Headless 모드 사용으로 창 없이 크롤링 하기

songsariya 2021. 1. 20. 21:02
728x90

 Headless라는 용어는 브라우저 창을 사용하지 않는다 라고 보시면 됩니다. 기본적으로 우리가 사용하는 브라우저는 html css js 파일 등을 불러와서 화면에 어떻게 그려줘야 할지 계산을 하고 우리에게 화면으로 보여줍니다. 하지만 GUI 환경이 아닌 곳에서 즉 ㄹ리눅스 서버와 같은 곳에서는 화면이 존재하지 않기 때문에 일반적인 방식으로 브라우저를 사용할 수 없습니다. 그래서 사용되는 게 Headless 모드입니다. 화면을 가상으로 랜더링 해서 실제 브라우저에서 사용하는 것처럼 작동하는 방법입니다.

 

 기존에 작업했던 소스입니다.

<?php

namespace Facebook\WebDriver;

use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;

require_once('vendor/autoload.php');

// This is where Selenium server 2/3 listens by default. For Selenium 4, Chromedriver or Geckodriver, use http://localhost:4444/
$host = 'http://localhost:4444/wd/hub';

$capabilities = DesiredCapabilities::chrome();

$driver = RemoteWebDriver::create($host, $capabilities);

// 네이버 데이터랩 쇼핑인사이트
$driver->get('https://datalab.naver.com/shoppingInsight/sCategory.naver');
sleep(2);

// 인기검색어 1-20 까지 텍스트 가져오기
for($j = 1; $j < 21; $j++ ) {
        $element = $driver->findElement(WebDriverBy::xpath('//*[@id="content"]/div[2]/div/div[2]/div[2]/div/div/div[1]/ul/li['.$j.']/a'));
        $sample[] = $element->gettext();
}

print_r($sample);

// close the browser
$driver->quit();

 

여기서 Headless 옵션을 추가해주시면 됩니다.

 

<?php

namespace Facebook\WebDriver;

use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;

require_once('vendor/autoload.php');

// This is where Selenium server 2/3 listens by default. For Selenium 4, Chromedriver or Geckodriver, use http://localhost:4444/
$host = 'http://localhost:4444/wd/hub';


// HEADLESS 모드 옵션 추가 시작 
$options = new ChromeOptions();
$options->addArguments(['--headless']);

$capabilities = DesiredCapabilities::chrome();
$capabilities->setCapability(ChromeOptions::CAPABILITY_W3C, $options);
// HEADLESS 모드 옵션 추가 종료

$driver = RemoteWebDriver::create($host, $capabilities);

 /* 이하 동일한 내용 */

 

 위와 같이 Headless 옵션을 추가한 후에 프로그램을 실행시키면 기존에 동작했던 방법과 다르게 크롬창 뜨지 않고 실행되는 것을 확인하실 수 있습니다.

728x90
Comments