问题
I'm making an C# Windows Form Application with an Awesomium webbrowser inside it.
I'm trying to get some rows from an table and parse them to an array. The JSPart is running inside the browser fine.
Here's the code that i use inside C#:
JSObject villageRows = view.ExecuteJavascriptWithResult("document.getElementById(\"production_table\").getElementsByTagName(\"tbody\")[0].getElementsByTagName(\"tr\");");
if (villageRows == null)
{
return;
}
That returns now 2 tr
rows inside Chrome, but that will be more later, so i was hoping that i could loop through the elements with an foreach, but i can't find any way to loop through it.
Does anybody got any idea?
回答1:
I would use an anonymous function in Javascript to parse the table and return the contents as an array of array of strings. This will be easier to parse in C#.
See http://jsfiddle.net/stevejansen/xDZQP/ for an example of parsing a table in Javascript. (Sidenote: I would check to see if your data source provides a REST API or similar to access this data; parsing HTML is really fragile.)
This is roughly how I would combine C# and JS to solve your problem (the C# is untested). Note you were using the wrong return type for 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/loop-through-awesomium-jsobject