HtmlElement使用C#获取具有特定ID的表

时间:2015-05-13 11:16:22

标签: c# htmlelements

我有简单的代码,可以读取html并从表中写入数据:

        foreach (HtmlElement hrel in testWebBrowser.Document.GetElementsByTagName("table"))
        {
                HtmlElementCollection coll2 = hrel.GetElementsByTagName("tr");
                Console.WriteLine(coll2[0].InnerText);
                Console.WriteLine(coll2[1].InnerText);
                Console.WriteLine(coll2[2].InnerText);
                Console.WriteLine(coll2[3].InnerText);                
        }

但我希望通过id阅读表格...我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用GetElementsById按ID获取HTML元素。

var util = require('util'),
  fs = require('fs'),
  Readable = require('stream').Readable;

function SymbolReadStream(filename, options) {
  if (!(this instanceof SymbolReadStream)) {
    return new SymbolReadStream(length, options);
  }

  Readable.call(this);
  this._readable = fs.createReadStream(filename, options);
}

util.inherits(SymbolReadStream, Readable); // inherit the prototype methods

SymbolReadStream.prototype._read = function() {
  var self = this;
  this._readable.on('readable', function() {
    var chunk;
    while (null !== (chunk = self._readable.read(1))) {
      self.emit('data', chunk);
    }
  });
  this._readable.on('end', function() {
    self.emit('end');
  });
};

var r = new SymbolReadStream("test.txt", {
  encoding: 'utf8',
});
r.on('data', function(el) {
  console.log(el);
});
r.on('end', function(el) {
  console.log('done');
});

答案 1 :(得分:1)

您是否尝试过GetElementById

HtmlElement table =  testWebBrowser.Document.GetElementById("TableID");
if (table != null)
{
    foreach (HtmlElement row in table.GetElementsByTagName("TR"))
    {
        // ...
    }
}