Python 和 Selenium 移动仿真

Ale*_*ana 9 python selenium emulation selenium-chromedriver selenium-webdriver

我正在尝试使用 Selenium 模拟和 Python 模拟 iPhone X 的 Chrome,如下所示:

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')
Run Code Online (Sandbox Code Playgroud)

但是,什么也没有发生:我的页面仍然是一个普通的浏览器页面,我不认为它是一个移动页面。

我的代码中缺少什么或有什么问题?

ben*_*era 8

您现在可能已经找到了答案,但这里有一个通用的答案:在您的代码示例中,您的驱动程序没有机会知道您希望它模拟另一个设备。这是完整的工作代码:

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')
Run Code Online (Sandbox Code Playgroud)

确保 Chrome 支持您的设备并且您的设备名称拼写正确。

如果此答案有帮助/有效,即使您已经有了解决方案,也请将其标记为如此。它只适用于以下程序员:)

贝尼。


小智 6

尝试这个。

iphoneX [宽度:375,高度:812,像素比: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)
Run Code Online (Sandbox Code Playgroud)