从C#中的HTML表中检索数据

我想从HTML文档中检索数据。 我正在从我几乎完成的网站上抓取数据,但在尝试从表中检索数据时遇到问题。 这是HTML代码

<TABLE <tBody <table .... </table <table .... </table
Service Number Status Status Date
1 Approved 03042014

我必须检索状态字段的数据它已批准并在SQL DB中写入表格标签中有许多表。表没有ID。如何我可以得到正确的表,行和单元这是我的代码

  HtmlElement tBody = WB.Document.GetElementById("middle_column"); if (tBody != null) { string sURL = WB.Url.ToString(); int iTableCount = tBody.GetElementsByTagName("table").Count; } for (int i = 0; i <= iTableCount; i++) { HtmlElement tb=tBody.GetElementsByTagName("table")[i]; } 

这里出了点问题请帮帮忙。

您是否对Webbrowser控件中显示的页面有任何控制权? 如果你做得更好,你可以为状态TD添加一个id字段。 然后你的生活会更容易。

无论如何,这里是你如何搜索表中的值。

 HtmlElementCollection tables = this.WB.Document.GetElementsByTagName("table"); foreach (HtmlElement TBL in tables) { foreach (HtmlElement ROW in TBL.All) { foreach (HtmlElement CELL in ROW.All) { // Now you are looping through all cells in each table // Here you could use CELL.InnerText to search for "Status" or "Approved" } } } 

但是,这不是一个好方法,因为您循环遍历每个表和每个表中的每个单元格以查找文本。 将此作为最后一个选项。

希望这可以帮助您获得一个想法。

我更喜欢使用动态类型和DomElement属性,但您必须使用.net 4+。

对于表格,这里的主要优点是您不必遍历所有内容。 如果您知道要查找的行和列,那么您可以按行号和列号来定位重要数据,而不是遍历整个表。

另一个很大的优点是你基本上可以使用整个DOM,阅读不仅仅是表的内容。 确保在javascript中使用小写属性,即使您使用的是c#。

 HtmlElement myTableElement; //Set myTableElement using any GetElement... method. //Use a loop or square bracket index if the method returns an HtmlElementCollection. dynamic myTable = myTableElement.DomElement; for (int i = 0; i < myTable.rows.length; i++) { for (int j = 0; j < myTable.rows[i].cells.length; j++) { string CellContents = myTable.rows[i].cells[j].innerText; //You are not limited to innerText; you have the whole DOM available. //Do something with the CellContents. } }