get i frame source using HtmlAgilityPack

.net c# html-agility-pack xml xpath

Question

I am trying to get all iFrame source urls on an html doc. I tried using HtmlAgilityPack with xpath - but i don't seem to be getting a list of sources.

HtmlAgilityPack.HtmlDocument myHtml= new HtmlDocument();
myHtml.LoadHtml(htmlString);

foreach (HtmlNode framesrc) in myHtml.DocumentNode.SelectNodes("//iframe/src"))
{
    srcCollection.add(framesrc);
}

Is my xpath wrong? Thanks!

Accepted Answer

Actually this opensource html parser uses query look like following query:

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();

HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//iframe[@src]");


foreach(var node in nodes){
    HtmlAttribute attr = node.Attributes["src"];
    Console.WriteLine(attr.Value);
}

Popular Answer

ifarme has attribute @src. So your XPath should be //iframe/@src. It will select @src of all iframe.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why