我正在制作一个带有 Awesomium 网络浏览器的 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# 中解析。
参见 http://jsfiddle.net/stevejansen/xDZQP/有关在 Javascript 中解析表格的示例。 (旁注:我会检查您的数据源是否提供 REST API 或类似的 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);
}
}
