selenium模拟手机错误

错误代码:

Message: Could not start a new session. Error while creating session with the driver service. Stopping driver service: Could not start a new session. Response code 400. Message: invalid argument: entry 0 of ‘firstMatch’ is invalid

这是一个广泛性错误解释,即传入参数有问题。

我一开始想法是想要模拟手机,所以传入参数里面我要带上具体型号,根据selenium的options内容,要配置在option内,
根据chrome官方文档提供的案例:

1
2
3
4
5
6
from selenium import webdriver
mobile_emulation = { "deviceName": "Nexus 5" }
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities = chrome_options.to_capabilities())

我看了下这块desired_capabilities这个命令已经在selenium 4下删除了,现在直接使用option即可。
修改下:

1
2
3
4
5
from selenium import webdriver
mobile_emulation = { "deviceName": "Nexus 5" }
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
self.driver = webdriver.Remote(self.remote_url, options=chrome_options)

其中:

chrome_options.add_experimental_option(“mobileEmulation”, mobile_emulation)
就是启动增加额外的option命令,你只需要将参数传入进去即可。
我之前的add_argument是命令开关行,支持列表可以在 Chrome Flags for Tooling内找到。