首页 > 解决方案 > 如何从 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 代码并使用它?

标签: c#androidxamarinwebviewanglesharp

解决方案


您可以使用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
    }
}

推荐阅读