7

I am looking to be able to selectively turn on and off certain images. I've come across the following article:

PhantomJS how to skip download resource

I've also found this article which is very similar using python:

Selenium driven by PhantomJS/Python

I am presuming that I can do this via webdriver.ExecutePhantomJS(string script, params object[] args).

What I don't know is if I need to create some page object first via the Selenium PageFactory and then call this function? How would I turn it off again. An example of how to do this would be very helpful.

Community
  • 1
  • 1
navarro_miguel
  • 151
  • 1
  • 2
  • 5

1 Answers1

5

I was just looking for something similar...

This, for example, will ignore all urls ending with ".png":

using (var driver = new PhantomJSDriver())
{
    const string phantomScript = "var page=this;page.onResourceRequested = function(requestData, request) { var reg =  /\\.png/gi; var isPng = reg.test(requestData['url']); console.log(isPng,requestData['url']); if (isPng){console.log('Aborting: ' + requestData['url']);request.abort();}}";
    var script = driver.ExecutePhantomJS(phantomScript);
    driver.Navigate().GoToUrl("https://www.google.com/");                
    driver.GetScreenshot().SaveAsFile("googlewithoutimage.png",ImageFormat.Png);
}   

note that the 'page' object that you're looking for is 'this' in the ExecutePhantomJS scope, also note that I'm writing to the log to get a better understanding of what's happening.

This gives you the flexibility to turn on or off images selectively, as you required.

Linkgoron
  • 4,866
  • 2
  • 26
  • 26
  • Do you know if one should be calling `Quit();` on the driver object? – edhedges Jul 26 '15 at 22:56
  • 1
    From my experience you should actually use Quit, and not just dispose (as otherwise, for me, the window stays open). What I usually do is create a PhantomQuiter disposable wrapper class for the driver, that has a Driver property that returns the driver. and the wrapper quits in its dispose. – Linkgoron Jul 28 '15 at 08:44
  • 2
    If anyone is trying out Selenium and PhantomJS for the first time like me then these are the NuGet packages to install http://i.imgur.com/8wc8QC4.png – Matthew Lock Aug 05 '15 at 23:57