2015-05-18 3 views
0

Черные списки URL в PhantomJS и GhostDriver довольно просты. Сначала инициализировать драйвер с обработчиком:URL-адреса черного списка и белого списка в HtmlUnitDriver

PhantomJSDriver driver = new PhantomJSDriver(); 
driver.executePhantomJS(loadFile("/phantomjs/handlers.js")) 

и настроить обработчик:

this.onResourceRequested = function (requestData, networkRequest) { 
    var allowedUrls = [ 
     /https?:\/\/localhost.*/, 
     /https?:\/\/.*\.example.com\/?.*/ 
    ]; 
    var disallowedUrls = [ 
     /https?:\/\/nonono.com.*/ 
    ]; 

    function isUrlAllowed(url) { 
     function matches(url) { 
      return function(re) { 
       return re.test(url); 
      }; 
     } 
     return allowedUrls.some(matches(url)) && !disallowedUrls.some(matches(url)); 
    } 

    if (!isUrlAllowed(requestData.url)) { 
     console.log("Aborting disallowed request (# " + requestData.id + ") to url: '" + requestData.url + "'"); 
     networkRequest.abort(); 
    } 
}; 

я не нашел хороший способ сделать это с HtmlUnitDriver. Существует ScriptPreProcessor, упомянутый в How to filter javascript from specific urls in HtmlUnit, но он использует WebClient, а не HtmlUnitDriver. Есть идеи?

ответ

0

Продлить HtmlUnitDriver и реализовать ScriptPreProcessor (для редактирования содержимого) и HttpWebConnection (для разрешения/блокирования URL-адреса):

public class FilteringHtmlUnitDriver extends HtmlUnitDriver { 

    private static final String[] ALLOWED_URLS = { 
      "https?://localhost.*", 
      "https?://.*\\.yes.yes/?.*", 
    }; 
    private static final String[] DISALLOWED_URLS = { 
      "https?://spam.nono.*" 
    }; 

    public FilteringHtmlUnitDriver(DesiredCapabilities capabilities) { 
     super(capabilities); 
    } 

    @Override 
    protected WebClient modifyWebClient(WebClient client) { 
     WebConnection connection = filteringWebConnection(client); 
     ScriptPreProcessor preProcessor = filteringPreProcessor(); 

     client.setWebConnection(connection); 
     client.setScriptPreProcessor(preProcessor); 

     return client; 
    } 

    private ScriptPreProcessor filteringPreProcessor() { 
     return (htmlPage, sourceCode, sourceName, lineNumber, htmlElement) -> editContent(sourceCode); 
    } 

    private String editContent(String sourceCode) { 
     return sourceCode.replaceAll("foo", "bar");  } 

    private WebConnection filteringWebConnection(WebClient client) { 
     return new HttpWebConnection(client) { 
      @Override 
      public WebResponse getResponse(WebRequest request) throws IOException { 
       String url = request.getUrl().toString(); 
       WebResponse emptyResponse = new WebResponse(
         new WebResponseData("".getBytes(), SC_OK, "", new ArrayList<>()), request, 0); 

       for (String disallowed : DISALLOWED_URLS) { 
        if (url.matches(disallowed)) { 
         return emptyResponse; 
        } 
       } 
       for (String allowed : ALLOWED_URLS) { 
        if (url.matches(allowed)) { 
         return super.getResponse(request); 
        } 
       } 
       return emptyResponse; 
      } 
     }; 
    } 
} 

Это позволяет одновременно редактировать содержание, и блокирование URL.

Смежные вопросы