CEFSHARP - ChromiumWebBrowser 获取表格行单元格值 [英] CEFSHARP - ChromiumWebBrowser on get table row cell values
问题描述
我解决了大部分问题,但我找不到解决其中一个问题的方法.以前,我使用 Windows WebBrowser 并在经销商面板的查询屏幕上获取表格结果.像这样;
I solved most of my problems, but I couldn't find a solution for one of them. Previously, I was using Windows WebBrowser and getting a table result on a query screen in a dealer panel. Like this;
foreach (HtmlElement htmlobj in webBrowser1.Document.GetElementsByTagName("Table"))
{
if (htmlobj.GetAttribute("className") == "table table-striped")
{
foreach (HtmlElement tr in htmlobj.GetElementsByTagName("tbody"))
{
foreach (HtmlElement td in tr.Children)
{
string s0 = td.Children[0].InnerText;
string s1 = td.Children[1].InnerText;
}
}
}
}
如何使用 ChromiumWebBrowser 执行此操作?
How can I do this with ChromiumWebBrowser?
非常感谢您的帮助...^_^
Thanks a lot for helps... ^_^
推荐答案
这可以在 CefSharp 中使用 EvaluateScriptAsync
,通过执行 JavaScript 来查找表的 td
元素并将它们作为数组返回,C# 将作为 List
This can be achieved in CefSharp using EvaluateScriptAsync
, by executing JavaScript to find the table's td
elements and return them as an array, which C# will receive as a List<object>
如果您还不知道,您通常必须等到页面的 MainFrame
加载后,才能执行任何 JavaScript,您可以像这样实现:
If you didn't already know, you have to usually wait until the page's MainFrame
has loaded before executing any JavaScript, which you could implement like:
//...
ChromiumWebBrowser browser = new ChromiumWebBrowser("https://example.com"); // <- Your URL there
browser.FrameLoadEnd += (sender, args) =>
{
// Wait for the MainFrame to finish loading
if(args.Frame.IsMain)
GetTable(); // method to call that executes JavaScript, etc
}
现在,这是我为 EvaluateScriptAsync
制作的代码,用于将 td
的 innerText
返回到 C# 中:
Now, this is the code I made for EvaluateScriptAsync
to return the td
's innerText
into C#:
// assuming "browser" is the ChromiumWebBrowser and you're ready to start executing JavaScript (see above code)
private void GetTable ()
{
const string script = @"(function(){
let table = document.querySelector('table.table.table-striped'); // <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
}
});
}
我制作了这个 HTML 示例来测试它,因为您没有提供任何内容:
I made this HTML example to test it on, as you didn't provide any:
<table class="table table-striped">
<tr>
<th>One</th>
<th>Two</th>
</tr>
<tr>
<td>This is 1st</td>
<td>This is 2nd</td>
</tr>
</table>
这篇关于CEFSHARP - ChromiumWebBrowser 获取表格行单元格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!