2010-08-13 13 views
24

Me gustaría obtener preventivamente el código HTML de una página web que se va a cargar en un webView, analizarlo usando expresiones regulares, y mostrar solo el código HTML que quiero, mientras dejando que la página web todavía piense que ha cargado todo.¿Es posible obtener el código HTML de WebView

¿Hay alguna manera de hacerlo en el WebViewClient.onLoadResource() o métodos similares?

EDIT: He intentado esto:

class MyJavaScriptInterface 
{ 
     @SuppressWarnings("unused") 
     public void showHTML(String html, Context context) 
     { 
      new AlertDialog.Builder(context) 
       .setTitle("HTML") 
       .setMessage(html) 
       .setPositiveButton(android.R.string.ok, null) 
      .setCancelable(false) 
      .create(); 
       pageHTML = html; 
     } 
} 

@Override 
    public void customizeWebView(final ServiceCommunicableActivity activity, final WebView webview, final SearchResult mRom) { 
     mRom.setFileSize(getFileSize(mRom.getURLSuffix())); 
     webview.getSettings().setJavaScriptEnabled(true); 
     MyJavaScriptInterface interfaceA = new MyJavaScriptInterface(); 
     webview.addJavascriptInterface(interfaceA, "HTMLOUT"); 
     WebViewClient anchorWebViewClient = new WebViewClient() 
     { 
      @Override 
      public void onPageFinished(WebView view, String url) 
      { 
       /* This call inject JavaScript into the page which just finished loading. */ 
       webview.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');"); 
       Pattern pattern = Pattern.compile("<h2>Winning Sc.+</h2></div>(.+)<br>", Pattern.DOTALL); 
       Matcher matcher = pattern.matcher(pageHTML); 
       matcher.find(); 

La interfaz nunca es llamado

Respuesta

10

Tuve que usar HttpClient. no hay galletas requiere, simplemente el análisis de HTML:

private String getDownloadButtonOnly(String url){ 
    HttpGet pageGet = new HttpGet(url); 

    ResponseHandler<String> handler = new ResponseHandler<String>() { 
     public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { 
      HttpEntity entity = response.getEntity(); 
      String html; 

      if (entity != null) { 
       html = EntityUtils.toString(entity); 
       return html; 
      } else { 
       return null; 
      } 
     } 
    }; 

    pageHTML = null; 
    try { 
     while (pageHTML==null){ 
      pageHTML = client.execute(pageGet, handler); 
     } 
    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

     Pattern pattern = Pattern.compile("<h2>Direct Down.+?</h2>(</div>)*(.+?)<.+?>", Pattern.DOTALL); 
     Matcher matcher = pattern.matcher(pageHTML); 
     String displayHTML = null; 
     while(matcher.find()){ 
      displayHTML = matcher.group(); 
     } 

    return displayHTML; 
} 

    @Override 
    public void customizeWebView(final ServiceCommunicableActivity activity, final WebView webview, final SearchResult mRom) { 
     mRom.setFileSize(getFileSize(mRom.getURLSuffix())); 
     webview.getSettings().setJavaScriptEnabled(true); 
     WebViewClient anchorWebViewClient = new WebViewClient() 
     { 

      @Override 
      public void onPageStarted(WebView view, String url, Bitmap favicon) { 
       super.onPageStarted(view, url, favicon); 
       String downloadButtonHTML = getDownloadButtonOnly(url); 
       if(downloadButtonHTML!=null && !url.equals(lastLoadedURL)){ 
        lastLoadedURL = url; 
        webview.loadDataWithBaseURL(url, downloadButtonHTML, null, "utf-8", url); 
       } 
      } 
+0

@pageHTML = client.execute (pageGet, handler); ¿Qué es cliente? –

+0

nevermind, HttpClient client = new DefaultHttpClient(); –

+0

@Aymon Fournier- ¿Cómo obtengo solo una línea de código fuente html de la página web? si obtengo una página de fuente completa, puede pasar tanto tiempo y no necesito obtener toda la línea, ¿me pueden ayudar? thx muchísimo –

5

Aquí hay un tutorial de Extracting HTML from a WebView no se olvide de leer la advertencia en el final del tutorial.

+0

Ese código no funciona –

+1

webview.addJavascriptInterface (new MyJavaScriptInterface(), "HTMLOUT"); \t \t WebViewClient anchorWebViewClient = new WebViewClient() { \t \t \t \t @ Override \t \t \t public void (vista WebView, String url) onPageFinished \t \t \t { \t \t \t/* Esta llamada de JavaScript en el página que acaba de terminar de cargar. */ \t \t \t webview.loadUrl ("javascript: window.HTMLOUT.showHTML (' '+ document.getElementsByTagName (' html ') [0] .innerHTML +'');"); –

+0

ese tutorial ha guardado mi trasero más de una vez ... gracias por publicarlo –

0

intenta agregar @JavascriptInterface antes public void showHTML (html cadena, el contexto Contexto)

0

En caso de que tenga la oportunidad de influir en la parte del servidor en la que recibe una página de, puede solicitar redirigir a una página en particular en caso de error. En su WebViewClient puede detectar esta redirección y usarla como una señal de error.

Cuestiones relacionadas