如何在seleniumlibrary / robotframework上禁用加载外部URL

时间:2013-03-08 13:50:17

标签: selenium-webdriver robotframework

我开始玩Seleniumlibrary测试(使用robotframework运行),并且我们的网站上有广告和指标等,每次运行测试时,这些网址都会被加载。

有没有办法告诉selenium / robotframework不加载某些类型的URL或阻止它加载外部资源(即不是来自localhost的所有内容)。

2 个答案:

答案 0 :(得分:8)

您可以使用browsermob-proxy执行此操作。安装完成后,只需设置代理并设置黑名单。

ProxyServer server = new ProxyServer(9000)
server.start();
final DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, server.seleniumProxy());
//Send a 200 for all requests to the facebook cdn
server.blacklistRequests("http://.*\\.fbcdn.net/.*", 200); 
//Finish setting up your driver
WebDriver driver = new SomeDriverImpl(capabilities);

我相信以下内容适用于this python wrapper(正则表达式可能略有不同):

from browsermobproxy import Server
server = Server("path/to/browsermob-proxy")
server.start()
proxy = server.create_proxy()
proxy.blacklist('http://.*\\.fbcdn.net/.*', 200)
from selenium import webdriver
profile  = webdriver.FirefoxProfile()
profile.set_proxy(proxy.selenium_proxy())
driver = webdriver.Firefox(firefox_profile=profile)
...
proxy.stop()
driver.quit()

答案 1 :(得分:0)

这现在可以在 Chrome 中用两行代码完成:

driver.execute_cdp_cmd('Network.setBlockedURLs', {"urls": ["www.baidu.com"]})
driver.execute_cdp_cmd('Network.enable', {})