How can I utilize webview2 to retrieve webpage content in C#?
To use WebView2 to retrieve web content, you first need to add the WebView2 control to your C# project. Then, you can write code to load a webpage and retrieve its content. Below is a simple example code:
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);
}
}
}
In the example above, we created a Windows window application and initialized the WebView2 control and loaded a specific webpage when the window is loaded. In the WebView1_NavigationCompleted event, we used the ExecuteScriptAsync method to run JavaScript code, retrieve the HTML content of the webpage, and display it on the console. You can further manipulate the retrieved webpage content as needed.