Csharp/C#教程:从C#中的HTML表中检索数据分享


从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#。

上述就是C#学习教程:从C#中的HTML表中检索数据分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 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. } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/949741.html

(0)
上一篇 2021年11月17日
下一篇 2021年11月17日

精彩推荐