0

我可以使用此代码从 cefsharp chromiumwebbrowser 获取表的第一行的 td 值,但我需要所有行的值。如何获取每一行的值?感谢您的回答。

private void GetTable ()
 {
const string script = @"(function(){
    let table = document.querySelector('table'); // <table class='table table-striped'>
    let td = table.getElementsByTagName('td');
    return [ td[0].innerText, td[1].innerText ];
})();";
browser.GetMainFrame().EvaluateScriptAsync(script).ContinueWith(x =>
{
    var response = x.Result;

    if (response.Success && response.Result != null)
    {
        // We cast values as CefSharp wouldn't know what to expect
        List<object> jsResult = (List<object>)response.Result;

        string s1 = (string)jsResult[0]; // td[0].innerText
        string s2 = (string)jsResult[1]; // td[1].innerText

        Console.WriteLine("s1: " + s1);
        Console.WriteLine("s2: " + s2);
        // In my example HTML page, it will output:
        // s1: This is 1st
        // s2: This is 2nd
    }
});

}

我从https://stackoverflow.com/a/55731493/3809268获得此代码感谢此代码所有者。

4

1 回答 1

0

首先,您需要更改script. 尝试这个:

.
.
.
let td = table.getElementsByTagName('td');
let arr = [];
for (var i = 0; i < td.length; i++) {
    arr.push(td[i].innerText);
}
return arr;

然后更改 C# 代码:

.
.
.
if (response.Success && response.Result != null)
{
    List<object> jsResult = (List<object>)response.Result;

    foreach (var item in jsResult)
    {
        Console.WriteLine("s: " + item.ToString());
    }
}

script我们创建innerText了每个td元素的数组。然后用于foreach从列表中读取每个元素。

于 2021-07-14T12:12:53.993 回答