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

时间:2015-01-07 17:56:14

标签: c# winforms web timer

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

所以我有一个ListBox(应该包含名称)。 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

2 个答案:

答案 0 :(得分:4)

您可以使用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();
    }
}

答案 1 :(得分:0)

使用Selenium。主要用于测试, 甚至更好地报废数据。 从经验谈起。