新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

C#如何用webview2获取网页内容,C#如何用for循环给textBox赋值

发布时间:2024-02-26 17:32:29

C#如何用webview2获得网页内容

要使用WebView2获得网页内容,首先需要在你的C#项目中添加WebView2控件。接下来,你可以编写代码来加载网页并获得其内容。以下是一个简单的示例代码:

using Microsoft.Web.WebView2.Core;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebView2Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            webView1.NavigationCompleted += WebView1_NavigationCompleted;
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            await webView1.EnsureCoreWebView2Async();
            webView1.Source = new Uri("https://www.example.com");
        }

        private async void WebView1_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            string htmlContent = await webView1.CoreWebView2.ExecuteScriptAsync("document.documentElement.outerHTML");
            Console.WriteLine(htmlContent);
        }
    }
}

在上面的示例中,我们创建了一个Windows窗体利用,并在窗体加载时初始化WebView2控件并加载指定的网页。在WebView1_NavigationCompleted事件中,我们使用ExecuteScriptAsync方法来履行JavaScript代码,获得网页的HTML内容并将其输出到控制台。你可以根据需要对获得的网页内容进行进一步操作。