Skip to content Skip to sidebar Skip to footer

How To Extract Html Links From Html File In C#?

Can anyone help me by explaining how to extract urls/links from HTML File in C#

Solution 1:

look at Html Agility Pack

HtmlDocument doc = newHtmlDocument(); 
doc.Load("file.htm");  
foreach(HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]")) 
{
    HtmlAttribute att = link.Attributes["href"];
    yourList.Add(att.Value)  
}  
doc.Save("file.htm");

Solution 2:

Use HTMLAgility Pack...

privateList<string> ParseLinks(string html)
    {
        var doc = newHtmlDocument(); 
        doc.LoadHtml(html);
        var nodes = doc.DocumentNode.SelectNodes("//a[@href]");
        return nodes == null ? newList<string>() : nodes.ToList().ConvertAll(r => r.Attributes.ToList().ConvertAll(i => i.Value)).SelectMany(j => j).ToList();
    }

It works for me.

Solution 3:

You can use an HTQL COM object and query the page using query: <a>:href

HTQLCOMLib.HtqlControl h = new HTQLCOMLib.HtqlControl();
string page = "<html><body><ahref='test1.html'>test1</a><ahref='test2.html'>test2</a></body></html>";
h.setSourceData(page, page.Length);
h.setQuery("<a>: href ");
for (h.moveFirst(); 0 == h.isEOF(); h.moveNext() )
{
     MessageBox.Show(h.getValueByIndex(1));
}

It will show messages of:

test1.html

test2.html

Post a Comment for "How To Extract Html Links From Html File In C#?"