引言
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之后,加載的插件可能無法運行。
在網(wǎng)上找了一圈資料,概括起來就是selenium chrome是不支持headless模式下加載插件的。
原因
翻了一下stackoverflow,里面有chromium的開發(fā)提到:
We’ve decided against implementing extension support in headless mode for now because supporting all the required features is rather complex.
大致是headless模式支持插件必需的特性相當(dāng)復(fù)雜。
另外一位chromium的開發(fā)更加細致地說明了這一點:
- 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中,只有部分實現(xiàn)的方式是目前可以在無頭chrome中重用它們。(換言之就是大部分還沒能做到重用)
- Changing this requires a lot of refactoring that doesn’t seem justified given the benefit we’d gain. 支持這一特性需要大量的重構(gòu),不合理(我們又不996,??)。
最新方式
上述提到的原因還是在2020年的。都2023年了,foxfire都老早支持headless加載插件了,不會chromiun還沒有實現(xiàn)吧。
果然,在這篇官方博客中,新的headless被提出。即文章來源:http://www.zghlxwxcb.cn/news/detail-635973.html
- 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()
總結(jié)
如果你的代碼使用headless無法正常加載插件,檢查下代碼中的headless配置,被將其設(shè)置為最新的方式。文章來源地址http://www.zghlxwxcb.cn/news/detail-635973.html
chrome_options.add_argument("--headless=new")
到了這里,關(guān)于Selenium chrome headless模式下加載擴展的問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!