引言
   
Selenium headless是比较常用的自动化测试手段,但是在很长一段时间无法加载扩展。本文将介绍Selenium chrome如何加载扩展以及headless模式下加载扩展的问题及解决方式。
    
    
    加载扩展
   
chrome_option = webdriver.ChromeOptions()
# 方式一
chrome_option.add_argument("--user-data-dir="+plugin_path)
# 方式二
chrome_options.add_extension(plugin_path)
# 方式三
chrome_options.add_argument('load-extension='+plugin_path)
    推荐使用第三种方式。
    
    另外chrome安装的插件在C:\Users(username)\AppData\Local\Google\Chrome\User Data\Default\Extensions 下可找到
   
    
    
    headless模式下加载插件失败
   
    在正常模式下加载插件是运行正常的,然而切换到headless之后,加载的插件可能无法运行。
    
    在网上找了一圈资料,概括起来就是selenium chrome是不支持headless模式下加载插件的。
   
    
    
    原因
   
    翻了一下stackoverflow,里面有chromium的开发提到:
    
    We’ve decided against implementing extension support in headless mode for now because supporting all the required features is rather complex.
    
    大致是headless模式支持插件必需的特性相当复杂。
   
另外一位chromium的开发更加细致地说明了这一点:
- A lot of extension APIs are specific to non-headless browsers, so can’t be supported in headless chrome. 很多插件的api是针对有界面的浏览器的,因此headless chrome难以支持插件。
- Of the APIs we could feasibly support, only parts are implemented in such a way that we can currently reuse them for headless chrome. 在可以支持的api中,只有部分实现的方式是目前可以在无头chrome中重用它们。(换言之就是大部分还没能做到重用)
- Changing this requires a lot of refactoring that doesn’t seem justified given the benefit we’d gain. 支持这一特性需要大量的重构,不合理(我们又不996,?)。
    
    
    最新方式
   
    上述提到的原因还是在2020年的。都2023年了,foxfire都老早支持headless加载插件了,不会chromiun还没有实现吧。
    
    果然,在这篇
    
     官方博客
    
    中,新的headless被提出。即
   
- before
chrome_options = ChromeOptions()
chrome_options.headless = True
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
- after
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
    
    
    总结
   
如果你的代码使用headless无法正常加载插件,检查下代码中的headless配置,被将其设置为最新的方式。
chrome_options.add_argument("--headless=new")
 
