c# - 如何从 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 检查并加载没有问题)。
- 如何调用像“OnPageFinishedLoading”这样的事件?
- 如何从 WebView 中提取 HTML 代码并使用它?
解决方案
您可以使用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
}
}
推荐阅读
- mysql - SQL Server - MySQL 迁移错误:不正确的字符串值:'\xF4\x80\x82\x83...'
- php - 在 PHP 中嵌套 MySQLi 的正确方法
- azure-media-services - Azure 媒体播放器在悬停或鼠标悬停时显示控件
- node.js - 如果没有中间件处理,传递给“next”的错误会发生什么?
- reactjs - 如何使用 React 和 Firebase 托管在 SPA 上提供 robots.txt?
- android - ViewPager 加载不同的片段
- python - for 循环中的 Scrapy 请求响应仅获得一个值
- python - 切片数据帧时出现 KeyError
- angular - 在 node_modules 下的文件中所做的更改
- python-3.x - keras 中的多类预测顺序