Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 569
Alex Dana Avatar asked May 08 '20 14:05

Alex Dana


People also ask

Can I use python with selenium?

Selenium supports Python and thus can be utilized as Selenium WebDriver with Python for testing. Python is easy compared to other programming languages, having far less verbose. The Python APIs empower you to connect with the browser through Selenium.


2 Answers

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.

like image 61
benicamera Avatar answered Oct 19 '22 19:10

benicamera


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)
like image 5
bbokkun Avatar answered Oct 19 '22 18:10

bbokkun