Colaboratoryでseleniumを使う

Googleが提供するColaboratoryでseleniumを使いたい方に向けた記事です。

seleniumなどのインストール

!apt-get update
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
!pip install selenium

seleniumなどの初期設定

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import time

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--disable-popup-blocking")
driver = webdriver.Chrome('chromedriver',options=options)
driver.set_window_size('1000', '1000')
driver.set_script_timeout(5)
driver.implicitly_wait(5) # 要素が見つかるまでの待ち時間を設定する

URLにアクセスし、内容をBeautiful Soupに渡して表示

driver.get("読み込みたいURL")
time.sleep(0.5)

html = driver.page_source.encode('utf-8')
sp = BeautifulSoup(html, "html.parser")
print(sp.prettify())