Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# example of using PhantomJS webdriver ExecutePhantomJS to filter out images

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.

like image 554
navarro_miguel Avatar asked Aug 21 '14 03:08

navarro_miguel


1 Answers

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.

like image 83
Linkgoron Avatar answered Sep 27 '22 19:09

Linkgoron