Descargo un sitio html con WebClient y downloadString () y luego trato de obtener todos los enlaces entre ellos y ellos en una lista.
Después de algunos intentos y 2 horas de trabajo, 1 vez obtuve todos los enlaces, a veces solo obtengo uno y otras no.
Aquí hay una muestra de mi código: simplemente dejo el Bloqueo de captura para una mejor legibilidad.
List<string> getLinks = new List<string>();
for (int i = 0; i < wikiUrls.Length; i++)
{
try
{
string download = client.DownloadString(wikiUrls[i]);
string searchForDiv = "<div class=\"wiki\">";
int firstCharacter = download.IndexOf(searchForDiv);
//if wiki doens't exists, go to next element of for loop
if (firstCharacter == -1)
continue;
else
{
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(download);
string nodes = String.Empty;
var div = document.DocumentNode.SelectSingleNode("//div[@class=\"wiki\"]");
if (div != null)
{
getLinks = div.Descendants("a").Select(node => node.GetAttributeValue("href", "Not found \n")).ToList();
output.Text = string.Join(" ", getLinks);
}
}
}
Entiendo. Eso es porque
getLinks = div.Descendants("a").Select(node => node.GetAttributeValue("href", "Not found \n")).ToList();
GetLinks siempre se sobrescribió, porque está en un bucle for. Lo resolví con esto:
getLinks.AddRange(div.Descendants("a").Select(node => node.GetAttributeValue("href", String.Empty)).ToList());