从网页获取特定数据
本文关键字:数据 获取 网页 | 更新日期: 2023-09-27 18:00:27
我有一个页面,对于该页面,我需要从另一个不同的页面获取值。
我只想在"Números Sortados"框中检索这6个数字。
到目前为止,我只成功地获得了整个网页与这个:
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中选择这些数字。
以下是使用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();