PHP 크롬 웹브라우저를 이용한 크롤링
다른 언어에선 셀레리움을 많이 사용하는듯 한데 PHP에서 페이스북에서 만든 웹드라이브를 사용합니다.
설치는 어렵지 않으며 여기선 윈도우용 PHP가 이미 설치 되어 있다고 가정하고 웹드라이브 설치 하는것 부터 진행 합니다.
▷ 윈도우용 컴포저 다운로드
https://getcomposer.org/Composer-Setup.exe
▷ 필요한 라이브러리 설치
composer require php-webdriver/webdriver
composer require facebook/webdriver
▷ 웹드라이브 설치 하기
https://chromedriver.chromium.org/downloads
https://googlechromelabs.github.io/chrome-for-testing/
▷ 버전이 맞지 않으면 아래와 같은 메시지를 만나게 된다.
PHP Fatal error: Uncaught Facebook\WebDriver\Exception\SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 112
<?php
require_once('vendor/autoload.php');
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\WebDriverBy;
$options = new ChromeOptions();
// Chrome 옵션 설정
// 필요한 추가 옵션이 있다면 여기에 추가
// 헤드리스 옵션을 주지 않으면 브라우저 실행을 볼 수 있다.
// $options->addArguments(['--headless']);
$options->addArguments(['--window-size=1920,1080']);
$userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36';
$options->addArguments(["--user-agent={$userAgent}"]);
// ChromeDriver와 연결
$driver = RemoteWebDriver::create($host, $options->toCapabilities());
// Google 홈페이지에 접속
// $driver->get('https://www.google.com');
// $searchBox = $driver->findElement(WebDriverBy::name('q'));
// $searchBox->sendKeys('PHP WebDriver');
// $searchBox->submit();
// sleep(2);
sleep(2);
// 결과 페이지의 타이틀 출력
echo "Page title is: " . $driver->getTitle();
// 스크린샷 저장
$screenshotPath = __DIR__ . '/screenshot.png';
$driver->takeScreenshot($screenshotPath);
echo "Screenshot saved to: " . $screenshotPath . "\n";
// HTML 소스 저장
$htmlSource = $driver->getPageSource();
$htmlSourcePath = __DIR__ . '/page_source.html';
file_put_contents($htmlSourcePath, $htmlSource);
echo "HTML source saved to: " . $htmlSourcePath . "\n";
// 브라우저 종료
$driver->quit();
여기서 실행할때 다른 언어는 웹브라이브를 백그라운드로 실행 시키는데 여기선 그런것이 없기 때문에
수동으로 먼저 하나 실행 시켜야 합니다. 그리고 9515 포트가 활성화 되었는지 확인한 다음 위 PHP를 실행하면 됩니다.
아니면 스크립트를 하나 만들어 윈도우 start 명령으로 웹드라이브 실행 시키는것 만들고 위 PHP 실행 되도록 하나 만들면 되겠습니다.
관련링크