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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 08:27:42

问题


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.



来源:https://stackoverflow.com/questions/25417913/c-sharp-example-of-using-phantomjs-webdriver-executephantomjs-to-filter-out-imag

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