Can I automate Chrome request blocking using Selenium-webdriver for Ruby?

試著忘記壹切 提交于 2019-12-03 20:12:56

To block URLs from loading with Selenium with the DevTool API:

def send_cmd(driver, cmd, params={})
  bridge = driver.send(:bridge)
  resource = "session/#{bridge.session_id}/chromium/send_command_and_get_result"
  response = bridge.http.call(:post, resource, {'cmd':cmd, 'params': params})
  raise response[:value] if response[:status]
  return response[:value]
end

send_cmd(driver, "Network.setBlockedURLs", {'urls': ["*"]})
send_cmd(driver, "Network.enable")

It's not very well documented, but you can also implement request blocking by passing the host-resolver-rules option to chrome and mapping the domain to localhost or an invalid IP. Something like this should work for you:

options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--host-resolver-rules=MAP www.google-analytics.com 127.0.0.1')
driver = Selenium::WebDriver.for :chrome, options: options

Try https://github.com/lightbody/browsermob-proxy

I dont know if it can satisfy your requirement as I am no way a network expert, I do use browsermob-proxy extensively to capture network request along with selenium and there is a method to blacklist certain request

https://browsermob-proxy-py.readthedocs.io/en/stable/client.html#browsermobproxy.Client.blacklist

How to disable loading external urls on seleniumlibrary/robotframework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!