私はWebClientとdownloadString()を使ってhtmlサイトをダウンロードしてから、それらとの間のすべてのリンクをリストに入れようとします。
数回の試行と2時間の作業の後、1回はすべてのリンクを取得します。時には1つだけ取得し、時には何も取得しません。
ここで私のコードのサンプル - 私はちょうど良い読みやすさのためキャッチブロックを離れてみましょう。
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);
}
}
}
わかった。その理由は
getLinks = div.Descendants("a").Select(node => node.GetAttributeValue("href", "Not found \n")).ToList();
GetLinksは、forループ内にあるので、常に上書きされます。私はこれでこれを解決しました:
getLinks.AddRange(div.Descendants("a").Select(node => node.GetAttributeValue("href", String.Empty)).ToList());