[英]How to get data from the page in WebView? Android Xamarin
有一個我要從中獲取數據的網頁(不是我的並且沒有API)。 這樣的頁面的一個例子
https://warthunder.com/cn/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檢查並加載而沒有問題)。
您可以使用Custom WebViewClient和AddJavascriptInterface實現它:
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
}
}
通過NuGet添加此實用程序https://github.com/elcattivo/CloudFlareUtilities
簡單的工作代碼:
try
{
ClearanceHandler handler = new ClearanceHandler
{
MaxRetries = 2
};
HttpClient client = new HttpClient(handler);
string source = await client.GetStringAsync("https://warthunder.ru/ru/community/userinfo/?nick=Keofox");
var parser = new HtmlParser();
document = parser.ParseDocument(source);
}
catch (AggregateException ex) when (ex.InnerException is CloudFlareClearanceException)
{
}
catch (AggregateException ex) when (ex.InnerException is TaskCanceledException)
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.