Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all links on html page?

Tags:

c#

asp.net

Im working on a little hobby project. I already have written the code to get a url, download the header and return the mime type / content type.

However, the step before this is the one im stuck on - i need to retrieve the contents of all the urls on the page based inside a tag, and in quotes i.e.

...
<link rel='shortcut icon' href="/static/favicon.ico" type="image/x-icon" />
...

Would find the favicon link.

Is there anything helpful in the .net library or is this going to have to be a case for regex?

like image 644
maxp Avatar asked Feb 11 '10 22:02

maxp


People also ask

How do you get a link from inspect element?

All you have to do is right-click on the part of the page you want to change, then click the Inspect or Inspect Element link that appears on the bottom of the right-click menu.


4 Answers

I'd look at using the Html Agility Pack.

Here's an example straight from their examples page on how to find all the links in a page:

 HtmlWeb hw = new HtmlWeb();  HtmlDocument doc = hw.Load(/* url */);  foreach(HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))  {   } 
like image 133
womp Avatar answered Oct 14 '22 00:10

womp


You need to use the HTML Agility Pack.

For example:

var doc = new HtmlWeb().Load(url);
var linkTags = doc.DocumentNode.Descendants("link");
var linkedPages = doc.DocumentNode.Descendants("a")
                                  .Select(a => a.GetAttributeValue("href", null))
                                  .Where(u => !String.IsNullOrEmpty(u));
like image 44
SLaks Avatar answered Oct 14 '22 02:10

SLaks


There isn't anything built into the BCL, but fortunately you can use the HTML Agility Pack to accomplish this task quite simply.

As for your specific problem, please see Easily extracting links from a snippet of html with HtmlAgilityPack:

private List<string> ExtractAllAHrefTags(HtmlDocument htmlSnippet)
{
    List<string> hrefTags = new List<string>();

    foreach (HtmlNode link in htmlSnippet.DocumentNode.SelectNodes("//a[@href]"))
    {
        HtmlAttribute att = link.Attributes["href"];
        hrefTags.Add(att.Value);
    }

    return hrefTags;
}
like image 28
Andrew Hare Avatar answered Oct 14 '22 00:10

Andrew Hare


How about Regex?

<(a|link).*?href=(\"|')(.+?)(\"|').*?>

with flags IgnoreCase and SingleLine

See demo on systemtextregularexpressions.com regex.matches

like image 31
GRUNGER Avatar answered Oct 14 '22 02:10

GRUNGER