概要
Seleniumにおいて、モバイル端末の表示をエミュレートするための方法のメモです。
Chrome DevTools Protocol(CDP)の機能を使って、画面サイズとユーザエージェントの変更を行います。実機の完全な再現とはなりませんが、おおよその表示の目安にはなると思います。
環境
- Windows 10
- Python 3.10.4
- Selenium 4.1.3
- Chrome 101.0.4951.41
コード
emulate-mobile.py
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import os
import time
with webdriver.Chrome(service=Service(ChromeDriverManager().install())) as driver:
# iPhone 13用のパラメータ
viewport = {
"width": 390,
"height": 844,
"deviceScaleFactor": 3,
"mobile": True
}
ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1"
# デバイスのスクリーンサイズの設定
driver.execute_cdp_cmd("Emulation.setDeviceMetricsOverride", viewport)
# ユーザエージェントの変更
driver.execute_cdp_cmd("Emulation.setUserAgentOverride", {"userAgent": ua})
# 気象庁トップページにアクセス
driver.get('https://www.jma.go.jp/jma/index.html')
time.sleep(5)
# スクリーンショットを取得し保存
filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"screenshot_mobile.png")
driver.save_screenshot(filename)
- webdriver-managerを使って、最新のWebDriverをインストールします。
- CDPのEmulation.setDeviceMetricsOverrideで、スクリーンサイズの設定を行います。
- 個別のデバイス向けのパラメータは、PuppeteerのDeviceDescriptors.tsから拝借しました。
- Emulation.setUserAgentOverrideを使って、ユーザエージェントの変更をしています。
表示例
気象庁のページに「iPhone 13」と「iPad Pro11」のエミュレート設定でアクセスした際の表示例です。
iPhone 13
パラメータ
viewport = {
"width": 390,
"height": 844,
"deviceScaleFactor": 3,
"mobile": True
}
ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1"
iPad Pro 11
パラメータ
viewport = {
"width": 834,
"height": 1194,
"deviceScaleFactor": 2,
"mobile": True
}
ua = "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1"
参考
本記事の作成にあたり、以下を参考にさせていただきました。