要使用WebView2获取网页内容,首先需要在你的C#项目中添加WebView2控件
要使用WebView2获取网页内容,首先需要在你的C#项目中添加WebView2控件。接下来,你可以编写代码来加载网页并获取其内容。以下是一个简单的示例代码:
usingMicrosoft.Web.WebView2.Core;
usingSystem;
usingSystem.Threading.Tasks;
usingSystem.Windows.Forms;
namespaceWebView2Demo
{
publicpartialclassForm1:Form
{
publicForm1()
{
InitializeComponent();
webView1.NavigationCompleted+=WebView1_NavigationCompleted;
}
privateasyncvoidForm1_Load(objectsender,EventArgse)
{
awaitwebView1.EnsureCoreWebView2Async();
webView1.Source=newUri("https://www.example.com");
}
privateasyncvoidWebView1_NavigationCompleted(objectsender,CoreWebView2NavigationCompletedEventArgse)
{
stringhtmlContent=awaitwebView1.CoreWebView2.ExecuteScriptAsync("document.documentElement.outerHTML");
Console.WriteLine(htmlContent);
}
}
}
在上面的示例中,我们创建了一个Windows窗体应用,并在窗体加载时初始化WebView2控件并加载指定的网页。在WebView1_NavigationCompleted
事件中,我们使用ExecuteScriptAsync
方法来执行JavaScript代码,获取网页的HTML内容并将其输出到控制台。你可以根据需要对获取的网页内容进行进一步操作。
版权声明
本文仅代表作者观点,不代表博信信息网立场。