In this article, I will show you how to extract favicon from a web page using webpage URL. When you pass URL of web page to the function and it will result the icon of the website.
Step 1: Create an asp.net mvc project and right click on the controller folder and create a new controller and name it as HomeController. Inside the HomeController copy and paste the following code.
Home controller:
public JsonResult GetFavicon(string url)
{
string htmlCode;
string faviconurl="";
using (WebClient client = new WebClient())
{
htmlCode= client.DownloadString(url);
}
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlCode);
if (doc.DocumentNode != null)
{
foreach (HtmlNode link in doc.DocumentNode.SelectNodes(@"//link[@href]"))
{
HtmlAttribute att = link.Attributes["href"];
if (att.Value.EndsWith(".ico"))
{
faviconurl = att.Value;
}
}
}
return Json(faviconurl, JsonRequestBehavior.AllowGet);
}
Step 2: Right click on the index method and create a razor view and name it as index. Copy and paste the following code.
View.cstml:
$.ajax({
type: "POST",
url: '@Url.Action("GetFavicon", "Home", new { area = "" })',
contentType: "application/json;charset=utf-8",
data: "{'url': " +JSON.stringify($("#txtUrl").val()) + "}",
datatype: "JSON",
success: function (response) {
$("#favIcon").attr("src", response);
}
});
Post your comments / questions
Recent Article
- ImportError: cannot import name 'url' from 'django.conf.urls' - Django Error
- How to Enable Virtualization in BIOS Security Settings in Intel Processors For Android Studio?
- Dependency 'androidx.activity:activity:1.8.0' requires libraries and applications that depend on it.
- AttributeError: 'NoneType' object has no attribute 'get_text' - Python
- ModuleNotFoundError: No module named 'openpyxl' - Python
- How to get thumbnail from vimeo video URL in Python?
- Remove all special characters, punctuation except spaces from string - Python
- OSError: cannot write mode RGBA as JPEG- Python
Related Article