Amazon Linux上で、Python + Selenium + Headless Chromeを使用してWEBスクレイピングをしていきます。
前準備
まず、Amazon EC2で「Amazon Linux 2 AMI (HVM), SSD Volume Type – ami-009d6802948d06e52」を立ち上げます。
Chromeをインストールします。
sudo yum -y install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
ChromeDriverをインストールします。
wget https://chromedriver.storage.googleapis.com/2.45/chromedriver_linux64.zip unzip chromedriver_linux64.zip -d bin/
Python3とSeleniumをインストールします。
sudo yum install python3 sudo pip3 install Selenium
スクレイピング
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
def _main():
options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
driver.get('https://www.google.co.jp/')
search = driver.find_element_by_name('q')
search.send_keys('Python')
search.send_keys(Keys.RETURN)
time.sleep(3)
driver.save_screenshot('search_results.png')
driver.quit()
if __name__ == '__main__':
_main()
Googleで「Python」を検索して、検索結果のスクリーンショットを取ります。
python3 test.py
以下のようにスクリーンショットが取得できました。

日本語の文字化け
ただし、この状態で日本語を検索すると、以下のように文字化けしてしまいます。
search.send_keys('パイソン')

そこで、日本語フォントをインストールします。
sudo yum install ipa-gothic-fonts ipa-mincho-fonts ipa-pgothic-fonts ipa-pmincho-fonts
再度実行すると、文字化けすることなく、スクリーンショットを取得できました。
