C# example of using PhantomJS webdriver ExecutePha

2019-01-27 23:39发布

问题:

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.

回答1:

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.