我如何从网站上获取 table 的所有值

how do i get all the value of a table from a website

string Url = "http://www.dsebd.org/latest_share_price_scroll_l.php";
HtmlWeb web = new HtmlWeb();

HtmlDocument doc = web.Load(Url);
string a = doc.DocumentNode.SelectNodes("//iframe*[@src=latest_share_price_all\"]//html/body/div/table/tbody")[0].InnerText;

我已经试过了,但是在字符串 a 中发现了空值。

好的,这个让我困惑了一段时间,但我现在明白了。而不是从 http://www.dsebd.org/latest_share_price_scroll_l.php, you can get just the table data from http://www.dsebd.org/latest_share_price_all.php.

中拉出整个页面

尝试 select iframe 元素下 #document 节点的子元素时出现了一些奇怪的行为。有更多 xpath 经验的人可能能够解释这一点。

现在您可以使用以下 xpath 获取所有 table 行节点:

string url = "http://www.dsebd.org/latest_share_price_all.php";

HtmlDocument doc = new HtmlWeb().Load(url);
HtmlNode docNode = doc.DocumentNode;

var nodes = docNode.SelectNodes("//body/div/table/tr");

这将为您提供所有 table 行节点。然后你需要遍历你刚刚得到的每个节点,得到你想要的值。

例如,如果您想获取交易代码、高价和交易量,您可以执行以下操作:

//Remove the first node because it is the header row at the top of the table
nodes.RemoveAt(0);
foreach(HtmlNode rowNode in nodes)
{
    HtmlNode tradingCodeNode = rowNode.SelectSingleNode("td[2]/a");
    string tradingCode = tradingCodeNode.InnerText;

    HtmlNode highNode = rowNode.SelectSingleNode("td[4]");
    string highValue = highNode.InnerText;

    HtmlNode volumeNode = rowNode.SelectSingleNode("td[11]");
    string volumeValue = volumeNode.InnerText;

    //Do whatever you want with the values here
    //Put them in a class or add them to a list
}

XPath 使用基于 1 的索引,因此当您按编号引用 table 行中的特定单元格时,第一个元素位于索引 1,而不是像在 C# 数组中那样使用索引 0。