首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过Awesomium JSObject循环

通过Awesomium JSObject循环
EN

Stack Overflow用户
提问于 2014-02-14 15:53:03
回答 1查看 2.3K关注 0票数 1

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

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

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

代码语言:javascript
复制
JSObject villageRows = view.ExecuteJavascriptWithResult("document.getElementById(\"production_table\").getElementsByTagName(\"tbody\")[0].getElementsByTagName(\"tr\");");
if (villageRows == null)
{
    return;
}

这将返回Chrome内部的2行tr行,但稍后会更多,所以我希望可以用一个foreach循环元素,但我找不到任何方法来遍历它。

有人知道吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-15 20:32:35

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

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

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

代码语言:javascript
复制
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);
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21783735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档