import shutil from urllib.parse import quote from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service HTML = """ Selenium mobile emulation demo

Mobile layout ready

""" mobile_emulation = { "deviceMetrics": { "width": 390, "height": 844, "pixelRatio": 3.0, "mobile": True, "touch": True, }, "userAgent": ( "Mozilla/5.0 (Linux; Android 14; Pixel 8 Build/AP2A.240905.003) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/148.0.0.0 Mobile Safari/537.36" ), "clientHints": {"platform": "Android", "mobile": True}, } options = Options() options.add_argument("--headless=new") options.add_experimental_option("mobileEmulation", mobile_emulation) for browser_name in ("google-chrome", "chromium", "chromium-browser"): browser_path = shutil.which(browser_name) if browser_path: options.binary_location = browser_path break driver_path = shutil.which("chromedriver") service = Service(driver_path) if driver_path else Service() driver = webdriver.Chrome(service=service, options=options) try: driver.get("data:text/html;charset=utf-8," + quote(HTML)) metrics = driver.execute_script( """ return { title: document.title, viewport: `${window.innerWidth}x${window.innerHeight}`, screen: `${screen.width}x${screen.height}`, pixelRatio: window.devicePixelRatio, maxTouchPoints: navigator.maxTouchPoints, mobileUA: navigator.userAgent.includes("Mobile") }; """ ) print(f"title: {metrics['title']}") print(f"viewport: {metrics['viewport']}") print(f"screen: {metrics['screen']}") print(f"device_pixel_ratio: {metrics['pixelRatio']}") print(f"max_touch_points: {metrics['maxTouchPoints']}") print(f"user_agent_mobile: {metrics['mobileUA']}") finally: driver.quit()