Reputation: 1147
I'm trying to get the list of all the names from here (the champion link titles in the table) but I'm having no success.. Can anyone direct me what's wrong with this code please?
Thank you!
var url = "http://leagueoflegends.wikia.com/wiki/List_of_champions";
var web = new HtmlWeb();
var doc = web.Load(url);
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table[3]/tr"))
{
HtmlNode item = table.SelectSingleNode("//a");
Console.WriteLine(item.GetAttributeValue("title", false));
}
UPDATE:
Alright, I got it to work just fine with this code:
var url = "http://leagueoflegends.wikia.com/wiki/List_of_champions";
var web = new HtmlWeb();
var doc = web.Load(url);
foreach (HtmlNode item in doc.DocumentNode.SelectNodes("//table[3]/tr/td/span/a"))
{
Console.WriteLine(item.Attributes["title"].Value);
}
return true;
Thanks for your help!
Upvotes: 0
Views: 247
Reputation: 4468
I knocked up a quick and dirty example, tested and works flawlessly, you'll want to format the result a bit though:
protected void Page_Load(object sender, EventArgs e)
{
List<HtmlAgilityPack.HtmlNode> test = GetInnerTest();
foreach (var node in test)
{
Response.Write("Result: " + node.InnerHtml.ToString());
}
}
public List<HtmlAgilityPack.HtmlNode> GetInnerTest()
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.OptionFixNestedTags = true;
doc.Load(requestData("http://leagueoflegends.wikia.com/wiki/List_of_champions"));
var node = doc.DocumentNode.Descendants("span").Where(d => d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("character_icon")).ToList();
return node;
}
public StreamReader requestData(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
return sr;
}
You'll need to download HtmlAgilityPack and include a reference for it to work.
Upvotes: 1
Reputation: 11201
Please use the xpath this way
foreach (HtmlNode linkItem in doc.DocumentNode.SelectNodes("//table[3]/tr//a"))
{
Console.WriteLine(linkItem.Attributes["title"].Value());
Console.WriteLine(linkItem.Attributes["alt"].Value());
}
Upvotes: 1