Cerin
Cerin

Reputation: 64870

How to run Selenium Python in mobile emulation mode?

How do you use Selenium to open Chrome in mobile emulation mode?

According to these docs you should be able to start Chrome in the mobile emulation mode you can normally access through the Inspect panel, with:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
mobile_emulation = {
    "deviceMetrics": { "width": 360, "height": 640, "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(chrome_options=chrome_options)

However, testing this with the most recent version of Chrome and ChromeDriver shows it doesn't work. It opens Chrome just fine, but it's in normal desktop mode. All the mobile options appear to be completely ignored.

I can still enable mobile emulation manually in the browser Selenium creates, but that doesn't help me for automating a test.

Upvotes: 2

Views: 5090

Answers (1)

PDHide
PDHide

Reputation: 19989

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">TEST</button>

<script type="text/javascript">
        $('#test').on('touchend click',function(e){
  if(e.type=='click')
    alert('click triggered');
  else
    alert('touch triggered');
});
    </script>

copy above html to a file and open it from selenium.

Now run the code and you can see that you get touch triggered alert and not click triggered:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
mobile_emulation = {
    "deviceMetrics": {"width": 360, "height": 640, "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 = webdriver.ChromeOptions()

chrome_options.add_experimental_option(
    "mobileEmulation", mobile_emulation)

driver = webdriver.Chrome(options=chrome_options)

driver.get(
    "file:///C:/Users/prave/Desktop/push.html")

driver.find_element_by_tag_name("button").click()
input()

Output:

The browser looks like normal browser but the screen resolution will be of mobile device when you open any url usign driver.get("")

enter image description here

Upvotes: 2

Related Questions