如何从网站上的 table 检索数据?

How to retrieve data from a table on website?

我制作了一个 WinForms 应用程序,可以从网站上的 table 中获取姓名列表。我目前正在使用 WebBrowser 和 Timer。而且我认为这可以做得更顺畅、更快。 WebBrowser 运行缓慢(内置的旧 Internet Explorer),有时无法获取数据,我必须重新运行计时器。

所以我有一个列表框(应该包含名称)。 ListBox 称为 PlayerList。 然后我有一个按钮,它可以激活定时器来抓取数据。这是我的计时器代码。

private void UpdatePlayers_Tick(object sender, EventArgs e)
        {
            PlayerList.Items.Clear();
            if (this.Tibia.ReadyState == WebBrowserReadyState.Complete)
            {
                foreach (HtmlElement cell in this.Tibia.Document.GetElementsByTagName("tr"))
                {
                    string cls = cell.GetAttribute("className");
                    if (cls.StartsWith("Odd"))
                    {
                        dynamic oldname = cell.InnerText;
                        string[] strings = oldname.Split('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
                        string charnameonly = strings[0];
                        this.PlayerList.Items.Add(charnameonly);
                    }
                    else if (cls.StartsWith("Even"))
                    {
                        dynamic oldname = cell.InnerText;
                        string[] strings = oldname.Split('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
                        string charnameonly = strings[0];
                        this.PlayerList.Items.Add(charnameonly);
                    }
                }
            }
        } 

我想知道是否有人可以帮助我在没有 WebBrowser 或类似工具的情况下实现这一点。一些代码示例会非常好。

注意:我只想要玩家的名字。这是我从中获取数据的网站:http://www.tibia.com/community/?subtopic=worlds&world=Antica

您可以使用HtmlAgilityPack

var players = await GetPlayers();

async Task<List<List<string>>> GetPlayers()
{
    string url = "http://www.tibia.com/community/?subtopic=worlds&world=Antica";
    using (var client = new HttpClient())
    {
        var html = await client.GetStringAsync(url);
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);

        var table = doc.DocumentNode.SelectSingleNode("//table[@class='Table2']");
        return table.Descendants("tr")
                    .Skip(2)
                    .Select(tr => tr.Descendants("td")
                                    .Select(td => WebUtility.HtmlDecode(td.InnerText))
                                    .ToList())
                    .ToList();
    }
}

使用Selenium。它主要是为测试而设计的, 甚至更好地抓取数据。 经验之谈。