Alex Dana
Alex Dana

Reputation: 1297

Python and Selenium mobile emulation

I'm trying to emulate Chrome for iPhone X with Selenium emulation and Python, as follow:

from selenium import webdriver

mobile_emulation = { "deviceName": "iphone X" }

chrome_options = webdriver.ChromeOptions()

chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)

driver = webdriver.Chrome(r'C:\Users\Alex\PythonDev\chromedriver')

driver.get('https://www.google.com')

However, nothing happens: my page is still a normal browser page, and I don't see it as a mobile page.

What is missing or wrong in my code?

Upvotes: 14

Views: 22512

Answers (3)

benicamera
benicamera

Reputation: 804

You might have found an answer by now, but here's a general one: In your code example, your driver has no chance to know that you want it to emulate another device. Here's full working code:

from selenium import webdriver
mobile_emulation = { "deviceName": "your device" }
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Chrome(options=chrome_options) #sometimes you have to insert your execution path
driver.get('https://www.google.com')

Make sure that Chrome supports your device and your device name is spelled correctly.

Upvotes: 14

bbokkun
bbokkun

Reputation: 191

try this.

iphoneX [width:375, height:812, pixelRatio:3].

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

mobile_emulation = {
    "deviceMetrics": { "width": 375, "height": 812, "pixelRatio": 3.0 },
    "userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"
}

chrome_options = Options()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Chrome(
    executable_path="../chrome/chromedriver85", options=chrome_options
)

url = "https://google.com/"
driver.get(url)

Upvotes: 7

you need to write iPhone X, and you wrote iphone X that should fix it

Upvotes: 1

Related Questions