Python and Selenium mobile emulation

孤者浪人 提交于 2021-02-04 19:08:50

问题


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?


回答1:


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.

If this answer was helpful/worked, please mark it as so, even if you already have a solution. It's just for following programmers :)

Beni.




回答2:


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)



回答3:


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



来源:https://stackoverflow.com/questions/61681097/python-and-selenium-mobile-emulation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!