想要获取webview2和网页之间的响应内容,需要在CoreWebView2InitializationCompleted事件中重写一下WebResourceResponseReceivedAsync事件,如下
private void webView2_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e) {
//进行网址过滤,这里是用来获取税务网站的发票明细信息 webView2.CoreWebView2.AddWebResourceRequestedFilter("https://inv-veri.chinatax.gov.cn/*", CoreWebView2WebResourceContext.All); webView2.CoreWebView2.WebResourceResponseReceived += CoreWebView2_WebResourceResponseReceivedAsync; }
重写WebResourceResponseReceivedAsync,这里面可以做的事情有好多,我写的很乱,可以遍历e.request.headers和e.Response.Headers
由于网页会多次返回内容触发这个事件,所以根据实际情况进行过滤和判断吧。
private async void CoreWebView2_WebResourceResponseReceivedAsync(object sender, CoreWebView2WebResourceResponseReceivedEventArgs e) { string res = ""; //foreach (var current in e.Request.Headers) //{ // L1.Items.Add(current); //} // Headers in response received testnum += 1; if (e.Response != null && e.Response.StatusCode == 200) { if(num == 5) { Stream content = await e.Response.GetContentAsync(); StreamReader sr = new StreamReader(content, System.Text.Encoding.UTF8); string jsonText = sr.ReadToEnd(); if (jsonText.Contains("详见销货清单")) { rtx_html.Text = jsonText; //content.Seek(0,SeekOrigin.Begin); //StreamReader streamReader = new StreamReader(content); //while (streamReader.Peek() != -1) //{ // //读取文件中的一行字符 // string str = streamReader.ReadLine(); // messageBuilder.AppendLine(str); //} //streamReader.Close(); } //messageBuilder.AppendLine(jsonText); //using (var fileStream = File.Create("D:\\DOS\\"+testnum.ToString()+".txt")) //{ // content.Seek(0, SeekOrigin.Begin);//设置复制开始的地方 // content.CopyTo(fileStream); //} } }
jsonText中保存的就是销货清单中的明细信息,然后再慢慢转成表格就可以了标签:CoreWebView2,C#,webview2,StreamReader,content,网页,jsonText,Response,WebResourceRe From: https://www.cnblogs.com/wjbych/p/17503090.html