1

我正在制作一个 C# Windows 窗体应用程序,里面有一个 Awesomium 网络浏览器。

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

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

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

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

有人知道吗?

4

1 回答 1

4

我会在 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);
    }
}
于 2014-02-15T20:32:35.503 回答