webview2怎么实现嵌套抓取拦截请求

代码

private async void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
    { 
        var request = e.Request; 
        var url = request.Uri; var tet = "";
        if (url != txtwanneng.Text.ToString().Trim())
        {
            if (url != null && (url.EndsWith(".m3u8") || url.Contains(".m3u8")) && qflagurl==true)
            {   
                urlSet.Add(url); 
                // 开始处理队列
                ProcessQueue(); 
            }  
        } 
        if (urlSet.Count == 0|| !issuccessqiantaom3u8)
        {
            List<string> iframeSources = await GetAllIFrameSourcesAsync();
            // 使用逗号分隔连接所有的 src 字符串   // 将连接后的字符串再次拆分成数组
            string joinedSources = string.Join(",", iframeSources);
            string[] sourcesArray = joinedSources.Split(',');
            if (sourcesArray.Length > 1)//在这调控空的iframe
            {
                foreach (var src in sourcesArray)
                {
                    Console.WriteLine($"IFrame source: {src}");
                    var needurl = src;
                    Match match = Regex.Match(src, @"http[^""]*", RegexOptions.Singleline);
                    if (match.Success)
                    {
                        needurl = match.Value; 
                    } 
                    //不是本域名的嵌套应该都进去拦截看看 不管有几个链接,加载都应该单开一个重新加载
                    if (needurl != null && (needurl != txtwanneng.Text.ToString().Trim()) && qflag == false)//在这调控不是m3u8或者mp4的iframe 获取嵌套带url的
                    { 
                        tet = "嵌套加载获取中....\n"; 
                        qflag = true;
                        urlSet.Clear();
                        listBox1.Items.Clear();
                        webView21.Reload(); 
                        Uri quri;
                        if (Uri.TryCreate(needurl, UriKind.Absolute, out quri))
                        {
                            webView21.Source = quri;
                        }
                        else
                        {
                            MessageBox.Show("嵌套iframe链接出错,无法抓取");
                        }
                    }
                    // 这里可以进一步处理每个 iframe 的 src 属性,例如显示到界面上或者进行其他操作
                }
            }
        }
        //iframelist获取

    }
private async void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
    { 
        var request = e.Request; 
        var url = request.Uri; var tet = "";
        if (url != txtwanneng.Text.ToString().Trim())
        {
            if (url != null && (url.EndsWith(".m3u8") || url.Contains(".m3u8")) && qflagurl==true)
            {   
                urlSet.Add(url); 
                // 开始处理队列
                ProcessQueue(); 
            }  
        } 
        if (urlSet.Count == 0|| !issuccessqiantaom3u8)
        {
            List<string> iframeSources = await GetAllIFrameSourcesAsync();
            // 使用逗号分隔连接所有的 src 字符串   // 将连接后的字符串再次拆分成数组
            string joinedSources = string.Join(",", iframeSources);
            string[] sourcesArray = joinedSources.Split(',');
            if (sourcesArray.Length > 1)//在这调控空的iframe
            {
                foreach (var src in sourcesArray)
                {
                    Console.WriteLine($"IFrame source: {src}");
                    var needurl = src;
                    Match match = Regex.Match(src, @"http[^""]*", RegexOptions.Singleline);
                    if (match.Success)
                    {
                        needurl = match.Value; 
                    } 
                    //不是本域名的嵌套应该都进去拦截看看 不管有几个链接,加载都应该单开一个重新加载
                    if (needurl != null && (needurl != txtwanneng.Text.ToString().Trim()) && qflag == false)//在这调控不是m3u8或者mp4的iframe 获取嵌套带url的
                    { 
                        tet = "嵌套加载获取中....\n"; 
                        qflag = true;
                        urlSet.Clear();
                        listBox1.Items.Clear();
                        webView21.Reload(); 
                        Uri quri;
                        if (Uri.TryCreate(needurl, UriKind.Absolute, out quri))
                        {
                            webView21.Source = quri;
                        }
                        else
                        {
                            MessageBox.Show("嵌套iframe链接出错,无法抓取");
                        }
                    }
                    // 这里可以进一步处理每个 iframe 的 src 属性,例如显示到界面上或者进行其他操作
                }
            }
        }
        //iframelist获取

    }在这里CoreWebView2_WebResourceRequested我进行了一个获取当前webview的所有iframe的src属性,但是可能会有多个,如果重新使用同样的  webView21.Reload();去加载url,那么其他的url可能就加载不到了, 有什么办法,不管有几个链接,加载都应该单开一个webview重新加载 并且实现CoreWebView2_WebResourceRequested同样的功能

CoreWebView2_WebResourceRequested webview2怎么实现嵌套抓取拦截请求

在这里CoreWebView2_WebResourceRequested我进行了一个获取当前webview的所有iframe的src属性,但是可能会有多个,如果重新使用同样的 webView21.Reload();去加载url,那么其他的url可能就加载不到了, 有什么办法,不管有几个链接,加载都应该单开一个webview重新加载 并且实现CoreWebView2_WebResourceRequested同样的功能

方案一:使用多个 WebView 实例

  1. 创建新的 WebView 实例: 在 CoreWebView2_WebResourceRequested 事件中,每次遇到需要加载的新 URL 时,就创建一个新的 CoreWebView2 实例,并将新的 URL 设置为其 Source 属性。

  2. 管理 WebView 实例: 你可以使用一个列表或字典来存储所有创建的 WebView 实例,以便后续管理和访问。

    var newWebView  = new  WebView2();
                                newWebView.CoreWebView2InitializationCompleted += NewWebView_CoreWebView2InitializationCompleted;
                                await newWebView.EnsureCoreWebView2Async();
    
                                //listBox1.Items.Clear();
                                //newWebView.Reload();
                                // 将字符串 URL 转换为 Uri 对象
                                Uri quri;
                                if (Uri.TryCreate(needurl, UriKind.Absolute, out quri))
                                {
                                    newWebView.Source = quri;
                                }
                                else
                                {
                                    Console.WriteLine(needurl);
                                    MessageBox.Show("嵌套iframe链接出错,无法抓取");
                                }
    
        private void NewWebView_CoreWebView2InitializationCompleted(object sender, EventArgs e)
        {
            var newWebView = (WebView2)sender; 
            // 添加 NavigationStarting 事件处理程序
            newWebView.CoreWebView2.NavigationStarting += CoreWebView2_NavigationStarting; 
            // 订阅请求拦截事件
            newWebView.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);
            newWebView.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;
        }

CoreWebView2_NavigationStarting; 这俩是一样通用的 CoreWebView2_WebResourceRequest ;递归调用拦截请求

private async void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
    {
        //e.Request.Headers.SetHeader("Referer", "https://www.nanhuyt.com/v/135-1-1.html"); 
        // 获取请求
        var request = e.Request; 
        var url = request.Uri; var tet = "";
        if (url != txtwanneng.Text.ToString().Trim())
        {
            if (url != null && (url.EndsWith(".m3u8") || url.Contains(".m3u8")) && qflagurl==true)
            {  
                Match match = Regex.Match(url, @"http((?!http).)*m3u8", RegexOptions.Singleline);
                if (match.Success)
                {
                    url = match.Value; 
                }
                urlSet.Add(url);  
            // 延迟更新 ListBox(例如,每隔一段时间或者在所有请求完成后更新)
                //await System.Threading.Tasks.Task.Delay(100); // 等待一段时间以收集多个请求  
                UpdateListBox();

                lock (queueLock)
                {
                    requestQueue.Enqueue(url);
                }
                // 开始处理队列
                ProcessQueue();


}else if ((url.EndsWith("mp4") || url.EndsWith(".mp4") || url.Contains("mp4")) && qflagurl == true) {

                Match match = Regex.Match(url, @"http((?!http).)*\.mp4", RegexOptions.Singleline);
                if (match.Success)
                {
                    url = match.Value;
                }
                urlSet.Add(url);  
                UpdateListBox();
                //issuccessqiantaom3u8 = true;
                //qflag = false;
                lock (queueLock)
                {
                    requestQueue.Enqueue(url);
                }
                // 开始处理队列
                ProcessQueue();
            }
            else if(url== "http://127.0.0.1/")
            {
                MessageBox.Show("触发回环地址,此网站无法抓取噢"); 
                //UpdateListBox();
            }
            else
            {
                //urlSet.Add(url); 
                //UpdateListBox();
            }
        }  


if (urlSet.Count == 0|| !issuccessqiantaom3u8) {

            List<string> iframeSources = await GetAllIFrameSourcesAsync();
            // 使用逗号分隔连接所有的 src 字符串   // 将连接后的字符串再次拆分成数组
            string joinedSources = string.Join(",", iframeSources);
            string[] sourcesArray = joinedSources.Split(',');
            if (sourcesArray.Length > 1 && qflag == false|| sourcesArray.Length > nlength)//在这调控空的iframe
            {
                nlength = sourcesArray.Length;
                qflag = true;//会一直抓 解决办法1, 多抓两次,2 抓到了才结束 3等待完成
                foreach (var src in sourcesArray)
                {
                    Console.WriteLine($"IFrame source: {src}");
                    var needurl = src;
                    Match match = Regex.Match(src, @"http[^""]*", RegexOptions.Singleline);
                    if (match.Success)
                    {
                        needurl = match.Value;
                        //if (needurl.Contains(".m3u8"))
                        //                        {
                        //    Match match2 = Regex.Match(needurl, @"http((?!http).)*m3u8", RegexOptions.Singleline);
                        //    if (match2.Success)
                        //    {
                        //        needurl = match2.Value;
                        //    }
                        //}
                        //qflag3 = false; 
                    }
                    //if (src != null && (src.EndsWith("m3u8") || src.EndsWith("mp4") || src.Contains("url") || src.Contains("mp4") )&& qflag == false)//在这调控不是m3u8或者mp4的iframe 获取嵌套带url的
                    //不是本域名的嵌套应该都进去拦截看看 不管有几个链接,加载都应该单开一个重新加载
                    if (needurl != null && (needurl != txtwanneng.Text.ToString().Trim()) )//在这调控不是m3u8或者mp4的iframe 获取嵌套带url的
                    {

                        tet = "嵌套加载获取中....\n";
                        Sharing.setTips(tet);
                        Widget.Ssp.Invoke(Form1.PSetTxt, new object[]
                        {
                                1,
                        "嵌套加载获取中...."
                        });

                        urlSet.Clear();
                        var newWebView  = new  WebView2();
                        newWebView.CoreWebView2InitializationCompleted += NewWebView_CoreWebView2InitializationCompleted;
                        await newWebView.EnsureCoreWebView2Async();

                        //listBox1.Items.Clear();
                        //newWebView.Reload();
                        // 将字符串 URL 转换为 Uri 对象
                        Uri quri;
                        if (Uri.TryCreate(needurl, UriKind.Absolute, out quri))
                        {
                            newWebView.Source = quri;
                        }
                        else
                        {
                            Console.WriteLine(needurl);
                            MessageBox.Show("嵌套iframe链接出错,无法抓取");
                        }
                    }
                    // 这里可以进一步处理每个 iframe 的 src 属性,例如显示到界面上或者进行其他操作
                }
            }
        }
        //iframelist获取 

    }
    int nlength=2;

有个问题 就是sourcesArray正常情况下就是2个数组,正常执行下面的就行,我们通过qflag = true;阻止了第二次再次进入, 但是可能会出现第一次获取是两个数组,第二次GetAllIFrameSourcesAsync是三个数组,但是这个时候,qflag = true;已经为ture了,有没有办法

可以让在sourcesArray.Length > 1 这里 如果有sourcesArray.Length 更大的进来,就不要之前的sourcesArray,或者继续进入有办法吗

      List<string> iframeSources = await GetAllIFrameSourcesAsync();
     string joinedSources = string.Join(",", iframeSources);
        string[] sourcesArray = joinedSources.Split(',');
        if (sourcesArray.Length > 1 && qflag == false )//在这调控空的iframe
        { 
            qflag = true;//会一直抓 解决办法1, 多抓两次,2 抓到了才结束 3等待完成

一开始想的办法是抓取成功后,给一个变量过来判断进不进,应该也行

如果我要的是在方法体内部新建多个WebView2 ,但是我在外部怎么全部释放他们

单个实例可以外部声明 private WebView2 newwebview

List<WebView2> webViewList = new List<WebView2>();

// 使用 for 循环创建多个 WebView2 对象
for (int i = 0; i < 5; i++)
{
    WebView2 webView = new WebView2();
    await webView.EnsureCoreWebView2Async();
    webViewList.Add(webView);
}

// 对创建的 WebView2 对象进行操作或者释放资源
foreach (var webView in webViewList)
{
    // 进行其他操作或者释放资源
    webView.Dispose();
}

// 清空集合
webViewList.Clear();