如何从 webview2 获取 HtmlElementCollection

我的旧 WinForm 应用程序使用 HtmlElementCollection 来处理页面

        HtmlDocument doc = Browser.Document;
        HtmlElementCollection elems = doc.GetElementsByTagName("table");
        HtmlElement a = elems[0];
        int[] Hucrn = new int[] { 0, 1, 2, 3, 4, 5, 6, };
        HtmlElementCollection satirlar = a.GetElementsByTagName("tr");

我想使用 webview2。但我没有得到 htmlelementcollection。

有谁知道这样做的方法?

stack overflow How can I get an HtmlElementCollection from webview2
原文答案

答案:

作者头像

作为使用 JavaScript 与 DOM 交互的替代方法,您可以从 Nuget.org 安装 WebView2.DevTools.Dom 。任何人都可以免费使用。 GitHub 上的项目。

您的代码将类似于:

await webView.EnsureCoreWebView2Async();

 // Create one instance per CoreWebView2
 // Reuse devToolsContext if possible, dispose (via DisposeAsync) before creating new instance
 // Make sure to call DisposeAsync when finished or await using as per this example
// Add using WebView2.DevTools.Dom; to access the CreateDevToolsContextAsync extension method
await using var devToolsContext = await webView2Browser.CoreWebView2.CreateDevToolsContextAsync();

//Get all table elements
var tableElements = await devtoolsContext.QuerySelectorAllAsync<HtmlTableElement>("table");

var table = tableElements[0];

var body = await table.GetBodyAsync();
var rows = await body.GetRowsAsync().ToArrayAsync();

foreach (var row in rows)
{
    var cells = await row.GetCellsAsync().ToArrayAsync();

    foreach (var cell in cells)
    {
        await table.SetInnerHtmlAsync("Updated Div innerText");
    }
}

//Alternatively Get a reference to the HtmlCollection and use async enumerable
//Requires Net Core 3.1 or higher
var tableRowsHtmlCollection = await table.GetRowsAsync();

await foreach (var row in tableRowsHtmlCollection)
{
    var cells = await row.GetCellsAsync();
    await foreach (var cell in cells)
    {
        var newDiv = await devToolsContext.CreateHtmlElementAsync<HtmlDivElement>("div");
        await newDiv.SetInnerTextAsync("New Div Added!");
        await cell.AppendChildAsync(newDiv);
    }
}

//Alternatively use querySelector syntax to directly return all cells within a table
//https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector#examples
//Get all table elements
var tableCells = await devtoolsContext.QuerySelectorAllAsync<HtmlTableCellElement>("table td");

foreach (var cell in tableCells)
{
    await table.SetInnerHtmlAsync("Updated Div innerText");
}

Readme 中有更多详细信息和示例。我正在为那些从旧的 IE WebBrowser 移植的指南工作,它位于 https://github.com/ChromiumDotNet/WebView2.DevTools.Dom/discussions/3