循环通过Awesomium JSObject

我正在制作一个带有Awesomium webbrowser的C#Windows窗体应用程序。

我试图从表中获取一些行并将它们解析为数组。 JSPart在浏览器中正常运行。

这是我在C#中使用的代码:

JSObject villageRows = view.ExecuteJavascriptWithResult("document.getElementById(\"production_table\").getElementsByTagName(\"tbody\")[0].getElementsByTagName(\"tr\");"); if (villageRows == null) { return; } 

现在返回Chrome中的2 tr行,但这会更晚,所以我希望我可以用foreach遍历元素,但我找不到任何方法来循环它。

有人有任何想法吗?

我会在Javascript中使用匿名函数来解析表并将内容作为字符串数组的数组返回。 这将更容易在C#中解析。

有关在Javascript中解析表的示例,请参阅http://jsfiddle.net/stevejansen/xDZQP/ 。 (旁注:我会检查您的数据源是否提供REST API或类似的访问此数据;解析HTML非常脆弱。)

这大致是我将C#和JS结合起来解决您的问题(C#未经测试)。 请注意,您使用了错误的IWebView.ExecuteJavascriptWithResult返回类型。

 const string JAVASCRIPT = @"(function () { var table = document.getElementById('production_table'), records = []; if (table == null) return; table = table.getElementsByTagName('tbody'); if (table == null || table.length === 0) return; // there should only be one tbody element in a table table = table[0]; // getElementsByTagName returns a NodeList instead of an Array // but we can still use Array#forEach on it Array.prototype.forEach.call(table.getElementsByTagName('tr'), function (row) { var record = []; Array.prototype.forEach.call(row.getElementsByTagName('td'), function (cell) { record.push(cell.innerText); }); records.push(record); }); return records; })();"; JSValue result = view.ExecuteJavascriptWithResult(JAVASCRIPT); JSValue[] records; JSValue[] record; if (result.IsNull || !result.IsArray) return; records = (JSValue[])result; foreach(JSValue row in records) { if (row == null || row.IsNull || !row.IsArray) continue; record = (JSValue[])row; foreach(JSValue cell in record) { if (cell.IsNull || !cell.IsString) continue; System.Diagnostics.Debug.WriteLine((string)cell); } }