如何从WebView中的页面获取数据?安卓 Xamarin

博格丹·伊尔基夫

有一个网页(不是我的,也没有 API),我想从中获取数据。此类页面的示例

https://warthunder.com/en/community/userinfo/?nick=Keofox

必要的数据位于以下块中:

<ul class = "profile-stat__list-sb">
<li class = "profile-stat__list-item"> sb</li>
<li class = "profile-stat__list-item"> 93 </li>
<li class = "profile-stat__list-item"> 64 </li>
<li class = "profile-stat__list-item"> 5 </li>

以前一切都通过 AngleSharp 工作,但最近添加了 Cloudflare 的 DDoS 保护。因此,解析器不起作用。延迟,WebView 中的并行加载不成功。

唯一可能的解决方案(在我看来)是从 WebView 中已经加载的页面中提取 HTML 代码(在 WebView 中,页面通过 Cloudflare 检查并且加载没有问题)。

  1. 如何调用“OnPageFinishedLoading”之类的事件?
  2. 如何从 WebView 中提取 HTML 代码并使用它?
Leo Zhu - MSFT

你可以使用Custom WebViewClientAddJavascriptInterface来实现它:

protected override void OnCreate(Bundle savedInstanceState)
    {      
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity_other);           
        webView = FindViewById<WebView>(Resource.Id.webView1);
        webView.SetWebViewClient(new WebViewClientClass());
        WebSettings websettings = webView.Settings;
        websettings.JavaScriptEnabled = true;
        websettings.DomStorageEnabled = true;
        webView.AddJavascriptInterface(new Foo(this), "Foo");
        webView.LoadUrl("file:///android_asset/demo.html");
    }


class WebViewClientClass : WebViewClient
    {
        public override void OnReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, string host, string realm)
        {

        }
        public override void OnPageFinished(WebView view, string url)
        {
            view.LoadUrl("javascript:window.Foo.showSource("
                         + "document.getElementsByTagName('html')[0].innerHTML);");
            base.OnPageFinished(view, url);
        }

    }

class Foo : Java.Lang.Object
{
    Context context;

    public Foo(Context context)
    {
        this.context = context;
    }
    [JavascriptInterface]
    [Export]
    public void showSource(string html)
    {
        Log.Error("content", html);//here html is the HTML code
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章