我正在制作一个C# Windows窗体应用程序,里面有一个Awesomium浏览器。
我试图从一个表中获取一些行,并将它们解析为一个数组。JSPart正在浏览器内部运行。
下面是我在C#中使用的代码:
JSObject villageRows = view.ExecuteJavascriptWithResult("document.getElementById(\"production_table\").getElementsByTagName(\"tbody\")[0].getElementsByTagName(\"tr\");");
if (villageRows == null)
{
return;
}这将返回Chrome内部的2行tr行,但稍后会更多,所以我希望可以用一个foreach循环元素,但我找不到任何方法来遍历它。
有人知道吗?
发布于 2014-02-15 20:32:35
我将在Javascript中使用一个匿名函数来解析表,并将内容作为字符串数组返回。这将更容易在C#中解析。
有关在Javascript中解析表的示例,请参见http://jsfiddle.net/stevejansen/xDZQP/。(Sidenote:我会检查数据源是否提供REST或类似于访问这些数据;解析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);
}
}https://stackoverflow.com/questions/21783735
复制相似问题