Selenium:为不同浏览器设置远程webdriver用户代理
我想在Python
中使用远程驱动为不同的浏览器设置用户代理。
现在我没有远程Selenium的环境来试验以下代码,所以我想提前问一下,下面的代码片段是否正确。
我在网上找到了以下几种方法。
1. Firefox
capabilities = DesiredCapabilities.FIREFOX.copy()
capabilities['general.useragent.override'] = user_agent_string
driver = Remote(command_executor=server_url, desired_capabilities=capabilities)
上面的代码正确吗?
2. PHANTOMJS
# Start Service Phantomjs
# get service_url
capabilities = DesiredCapabilities.PHANTOMJS.copy()
capabilities['phantomjs.page.settings.userAgent'] = user_agent_string
driver = Remote(command_executor=service_url, desired_capabilities=capabilities)
上面的代码正确吗?
3. CHROME
#Not sure about this
capabilities = DesiredCapabilities.CHROME.copy()
capabilities['chrome.switches'] = ['--user-agent=' + user_agent_string]
driver = Remote(command_executor=server_url, desired_capabilities=capabilities)
如果这个方法不行(因为我在谷歌上发现了一些问题),
那么,
有没有其他方法?比如使用Chrome选项?该怎么做呢?
4. IE
Does it support or any need ?
另外,创建驱动实例后,能否动态地更改用户代理?
1 个回答
1
根据selenium的文档,改变用户代理(User Agent)在使用Firefox浏览器驱动时,最好的方法是通过Firefox配置文件来实现。你可以参考下面的Python代码:
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "some UA string")
driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.FIREFOX, browser_profile=profile)
在创建驱动实例后,可以动态改变用户代理吗?
目前的答案是不可以。
RemoteWebdriver只在会话开始时更新能力映射。我们不能在其他地方进行修改。