淘先锋技术网

首页 1 2 3 4 5 6 7

初始化webView,使其支持javascript

WebSettings settings = mWebView.getSettings();

settings.setJavaScriptEnabled(true);

添加一个js交互对象

mWebView.addJavascriptInterface(new JavaObjectJsInterface(), "java_obj");

public class JavaObjectJsInterface {

@JavascriptInterface // 要加这个注解,不然调用不到

public void onHtml(String html) {

}

}

添加一个WebViewClient监听状态,并且在完成时通过js调用java对象的方法

mWebView.setWebViewClient(new MyWebViewClient());

public class MyWebViewClient extends WebViewClient {

@Override

public void onPageFinished(WebView view, String url) {

super.onPageFinished(view, url);

Log.d(TAG, "onPageFinished: ");

mWebView.loadUrl("javascript:window.java_obj.onHtml('

'+document.getElementsByTagName('html')[0].innerHTML+'');");

}

}

通过jsoup提取标签,需要在app的build.gradle中添加:

implementation 'org.jsoup:jsoup:1.9.2' // 获取/解析html文本

在onHtml()中解析:

public void onHtml(String html) {

Document document = Jsoup.parseBodyFragment(html);

if (document != null) {

Log.d(TAG, "onHtml: 解析document成功");

Elements elements = document.select(".video");

if (elements != null && !elements.isEmpty()) {

Element element = elements.get(0);

String src = element.attr("src");

}

}

}