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.

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Do you know if one should be calling Quit(); on the driver object?
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.
If anyone is trying out Selenium and PhantomJS for the first time like me then these are the NuGet packages to install i.imgur.com/8wc8QC4.png

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.