LoginSignup
1
3

More than 1 year has passed since last update.

[Python]Seleniumでスマホ表示をエミュレートする

Posted at

概要

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)

表示例

気象庁のページに「iPhone 13」と「iPad Pro11」のエミュレート設定でアクセスした際の表示例です。

iPhone 13

screenshot_mobile.png

パラメータ
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

screenshot_mobile.png

パラメータ
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"

参考

本記事の作成にあたり、以下を参考にさせていただきました。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3