从网页获取特定数据

时间:2015-06-29 18:26:06

标签: c# html-parsing

我有一个page,对于该页面,我需要从另一个不同的页面获取值。

我只想将6个数字检索到“NúmerosSorteadados”框中。

到目前为止,我只是成功地获得了整个网页:

WebRequest request = WebRequest.Create("http://www1.caixa.gov.br/loterias/loterias/ultimos_resultados.asp");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
    html = sr.ReadToEnd();
}

之后,我无法从HTML中选择这些数字。

1 个答案:

答案 0 :(得分:1)

以下是使用HTMLAgilityPack获取数字的快捷方式:

public async Task<List<string>> GetNumbers()
{
    // Getting the number of microseconds since Jan 1st, 1970
    var microseconds = (long)(DateTime.UtcNow - (new DateTime(1970, 1, 1, 0, 0, 0))).TotalMilliseconds;
    // Creating the webrequest and passing the parameter
    var request =
        WebRequest.CreateHttp(
            string.Format(
                "http://www1.caixa.gov.br/loterias/loterias/megasena/megasena_pesquisa_new.asp?app={0}",
                microseconds));
    // Adding a cookie container otherwise you will be stuck in a redirect loop
    var jar = new CookieContainer();
    request.CookieContainer = jar;

    try
    {
        var response = await request.GetResponseAsync();
        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            var html = await sr.ReadToEndAsync();
            var document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(html);
            var nodes = document.DocumentNode.SelectNodes("//span [@class=\"num_sorteio\"]");
            var numbersNodes = nodes.Last().SelectNodes("//li");

            // selecting the last 6 nodes that represent the "Números Sorteados" numbers
            return numbersNodes.Select(node => node.InnerText).Skip(6).ToList();
        }
    }
    catch (Exception e)
    {
        // very basic exception handling.
        Console.WriteLine(e);
    }
    return null;
} 

并且调用函数它就像:

List<string> Numbers = await GetNumbers();