Memo

メモ > 技術 > 開発: Selenium > PHP版Selenium環境をCentOS7に構築

■PHP版Selenium環境をCentOS7に構築
■参考 PHPでChromeを操作(クロール)|743|note https://note.com/743/n/n7367632b1e19 CentOS7でPHP + facebook/php-webdriverでchromeを動かしてクローリング - Qiita https://qiita.com/tech31/items/11e7e7aee7d60df249fb ■Chromeのインストール
$ sudo su - # yum -y install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm # google-chrome --version Google Chrome 88.0.4324.96 # yum -y install ipa-gothic-fonts ipa-mincho-fonts ipa-pgothic-fonts ipa-pmincho-fonts … 日本語フォントをインストール # exit … rootでは実行できない $ google-chrome --headless --disable-gpu --dump-dom http://example.com/ <!DOCTYPE html> <html><head> <title>Example Domain</title> 〜中略〜 </body></html>
■Chromeドライバのインストール
$ sudo su - # wget https://chromedriver.storage.googleapis.com/88.0.4324.96/chromedriver_linux64.zip … バージョンはChromeに合わせる # unzip chromedriver_linux64.zip # sudo mv chromedriver /usr/local/bin/ # rm -f chromedriver_linux64.zip # exit $ chromedriver -v ChromeDriver 88.0.4324.96 (68dba2d8a0b149a1d3afac56fa74648032bcf46b-refs/branch-heads/4324@{#1784})
■プログラムを作成(Yahoo検索を自動化) Composerは導入済みとする
$ mkdir sample_php $ cd sample_php $ composer require phpunit/phpunit $ composer require facebook/webdriver
以下はテスト例 Windowsとは異なる指定を行っている箇所があるので注意
$ vi test.php
<?php require_once 'vendor/autoload.php'; use Facebook\WebDriver\Chrome\ChromeDriver; use Facebook\WebDriver\Chrome\ChromeOptions; use Facebook\WebDriver\Remote\DesiredCapabilities; use Facebook\WebDriver\Remote\RemoteWebDriver; use Facebook\WebDriver\WebDriverBy; use Facebook\WebDriver\WebDriverExpectedCondition; // Chromeドライバを環境変数に設定 putenv('webdriver.chrome.driver=/usr/local/bin/chromedriver'); // Linux用にパスを指定 // 非表示設定で起動 $option = new ChromeOptions(); $option->addArguments([ //'--no-sandbox', // rootの場合に必須 '--headless', '--disable-gpu', ('--window-size=800,600'), // 非表示でもスクリーンショットのサイズに反映 ]); $chrome = DesiredCapabilities::chrome(); $chrome->setCapability(ChromeOptions::CAPABILITY, $option); $driver = ChromeDriver::start($chrome); // 設定を反映してブラウザを起動 $driver = ChromeDriver::start($chrome); // 遷移 $driver->get('https://www.yahoo.co.jp/'); // 遷移されるまで待つ $driver->wait(10, 1000)->until(WebDriverExpectedCondition::urlContains('https://www.yahoo.co.jp/')); // テキストボックス入力 $driver->findElement(WebDriverBy::name('p'))->sendKeys('自動テスト'); // ボタン押下 $driver->findElement(WebDriverBy::className('_63Ie6douiF2dG_ihlFTen'))->click(); // タイトルが「検索結果」を含むものになるまで待つ $driver->wait()->until(WebDriverExpectedCondition::titleContains('検索結果')); // テキストを取得 $text = $driver->findElement(WebDriverBy::name('p'))->getAttribute('value'); // 結果を出力 echo 'TEXT:' . $text . "\n"; // スクリーンショットを撮影 $driver->takeScreenshot('yahoo.png'); // ブラウザを閉じる $driver->close();
■プログラムを実行
$ php test.php

Advertisement