How can I get a web site's favicon?

前端 未结 14 2078
旧巷少年郎
旧巷少年郎 2020-12-22 15:28

Simple enough question: I\'ve created a small app that is basically just a favourites that sits in my system tray so that I can open often-used sites/folders/files from the

相关标签:
14条回答
  • 2020-12-22 15:39

    The first thing to look for is /favicon.ico in the site root; something like WebClient.DownloadFile() should do fine. However, you can also set the icon in metadata - for SO this is:

    <link rel="shortcut icon"
       href="http://sstatic.net/stackoverflow/img/favicon.ico">
    

    and note that alternative icons might be available; the "touch" one tends to be bigger and higher res, for example:

    <link rel="apple-touch-icon"
       href="http://sstatic.net/stackoverflow/img/apple-touch-icon.png">
    

    so you would parse that in either the HTML Agility Pack or XmlDocument (if xhtml) and use WebClient.DownloadFile()

    Here's some code I've used to obtain this via the agility pack:

    var favicon = "/favicon.ico";
    var el=root.SelectSingleNode("/html/head/link[@rel='shortcut icon' and @href]");
    if (el != null) favicon = el.Attributes["href"].Value;
    

    Note the icon is theirs, not yours.

    0 讨论(0)
  • 2020-12-22 15:40

    http://realfavicongenerator.net/favicon_checker?site=http://stackoverflow.com gives you favicon analysis stating which favicons are present in what size. You can process the page information to see which is the best quality favicon, and append it's filename to the URL to get it.

    0 讨论(0)
  • 2020-12-22 15:42

    The SHGetFileInfo (Check pinvoke.net for the signature) lets you retrieve a small or large icon, just as if you were dealing with a file/folder/Shell item.

    0 讨论(0)
  • 2020-12-22 15:44
    HttpWebRequest w = (HttpWebRequest)HttpWebRequest.Create("http://stackoverflow.com/favicon.ico");
    
    w.AllowAutoRedirect = true;
    
    HttpWebResponse r = (HttpWebResponse)w.GetResponse();
    
    System.Drawing.Image ico;
    using (Stream s = r.GetResponseStream())
    {
        ico = System.Drawing.Image.FromStream(s);
    }
    
    ico.Save("favicon.ico");
    
    0 讨论(0)
  • 2020-12-22 15:48

    It's a good practice to minimize the number of requests each page needs. So if you need several icons, yandex can do a sprite of favicons in one query. Here is an example http://favicon.yandex.net/favicon/google.com/stackoverflow.com/yandex.net/

    0 讨论(0)
  • 2020-12-22 15:48

    Using jquery

    var favicon = $("link[rel='shortcut icon']").attr("href") ||
                  $("link[rel='icon']").attr("href") || "";
    
    0 讨论(0)
提交回复
热议问题