如何从WebView中检索HTML内容(作为string)

如何检索当前显示在WebView中的所有HTML内容?

我发现WebView.loadData()但我找不到相反的等价物(如WebView.getData())

请注意,我有兴趣检索我无法控制的网页的数据(即我不能注入一个JavaScript函数到这些页面,以便它将在WebView中调用一个Javascript接口)。

不幸的是,这样做并不容易。

请参阅如何从WebView获取网页内容?

你可以做一个HttpRequest到与你的WebView相同的页面,并得到响应。

你可以通过以下方式来实现

 final Context myApp = this; /* An instance of this class will be registered as a JavaScript interface */ class MyJavaScriptInterface { @SuppressWarnings("unused") public void processHTML(String html) { // process the html as needed by the app } } final WebView browser = (WebView)findViewById(R.id.browser); /* JavaScript must be enabled if you want it to work, obviously */ browser.getSettings().setJavaScriptEnabled(true); /* Register a new JavaScript interface called HTMLOUT */ browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT"); /* WebViewClient must be set BEFORE calling loadUrl! */ browser.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { /* This call inject JavaScript into the page which just finished loading. */ browser.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');"); } }); /* load a web page */ browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html"); 

你将在processHTML方法中获得整个Html的contnet。 它不会再提出网页的要求。 所以这样做也是更有效的方法。

谢谢。

 webView.evaluateJavascript("(function(){return window.document.body.outerHTML})();", new ValueCallback<String>() { @Override public void onReceiveValue(String html) { } }); 

您可以拦截由WebView所做的HTTP请求,然后修改HTML以包含您需要与HTML页面进行通信的任何JavaScript函数。 您可以通过WebViewClient的shouldInterceptRequest()方法拦截HTTP请求。

使用这种机制,您可以通过自己加载来访问加载的页面,在将其传递到WebView之前对其进行修改,甚至在需要时将其caching到本地。

你可以从webview通过JavaScriptInterface传递数据..我已经完成了。 将数据保存到一个静态variables,然后在android applcation下进行处理

添加到您的代码:

 private String getUrlSource(String site) throws IOException { //GNU Public, from ZunoZap Web Browser URL url = new URL(site); URLConnection urlc = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( urlc.getInputStream(), "UTF-8")); String inputLine; StringBuilder a = new StringBuilder(); while ((inputLine = in.readLine()) != null) a.append(inputLine); in.close(); return a.toString(); } 

那么让我们来说说如何获得Google的源代码:

 getURLSource("http://google.com");