我知道如何在Selenium webdriver中加载Chrome扩展程序,但是我没有看到任何帖子/博客描述如何从Selenium中运行Chrome扩展程序。
我需要显式地运行Chrome扩展程序/使其在Selenium中执行其功能。例如,我想使用这个扩展程序通过Selenium Webdriver清除Chrome浏览器的缓存。
我能做到吗?或者Selenium WebDriver只会帮助我将扩展程序加载到浏览器实例中并将其留在那里?
我知道如何在Selenium webdriver中加载Chrome扩展程序,但是我没有看到任何帖子/博客描述如何从Selenium中运行Chrome扩展程序。
我需要显式地运行Chrome扩展程序/使其在Selenium中执行其功能。例如,我想使用这个扩展程序通过Selenium Webdriver清除Chrome浏览器的缓存。
我能做到吗?或者Selenium WebDriver只会帮助我将扩展程序加载到浏览器实例中并将其留在那里?
当 Chrome 扩展程序被激活时,它已经在后台事件页上“运行”了。没有 API 可以通过编程方式单击该按钮。
如果您想要使用现有扩展的功能并减少工作量,则建议下载扩展的源代码并在源代码中插入一个额外的事件监听器。
Create a new HTML file, example_name.html
, and let it contain:
<script src="example_name.js"></script>
Create a new script file, example_name.js
, and let it call the extension's functionality, e.g.:
chrome.runtime.getBackgroundPage(function(bg) {
// Relevant function at the background page. In your specific example:
bg.clearCache();
});
web_accessible_resources
in the manifest file.Pack the extension again, e.g. using the GUI at chrome://extensions
or using
chrome.exe --pack-extension=directorycontainingextension
After creating directorycontainingextension.crx
, load this crx file in Chrome to know the extension ID. If you don't know how to load the crx file in Chrome, just visit https://robwu.nl/crxviewer/, select the crx file, open the F12 developer tools and copy the 32-character string at "Calculated extension ID: [extension ID here]".
(Starting from ChromeDriver 2.11, you can just zip the extension instead of packing it as a CRX file, and hard-code the extension ID in the manifest file by setting the "key"
attribute (this "key"
attribute is also printed to the F12 console by the CRX Viewer).)
chrome-extension://[扩展ID]/example_name.html
那么简单。chrome.webRequest
或chrome.declarativeWebRequest
API来拦截自定义URL并激活所需功能,只要页面请求此资源,就可以将URL放入<img>
中以激活扩展的功能。chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") #Now you can see the Extensions and the logins done are present
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.postMessage('clicked_browser_action', '*')");