2

How can I achieve the same functionality (in C#) like Facebook and Linkedin does when posting a url into your status?

As you can see below from Linkedin, you enter an URL and Linkedin automatically fetches the title, image and the content of that article truncated.

enter image description here

1

2 Answers 2

5

I use Html Agility Pack to parse the HTML. It's available as a NuGet package.

If you have a WebPage class defined like this:

public class WebPage
{
    public string Title { get; set; }
    public string PageUrl { get; set; }
    public string Text { get; set; }
}

You can use the following code for parsing the HTML:

public WebPage ParseHtml(string html, Uri uri)
{
    var document = new HtmlDocument();
    document.LoadHtml(html);

    // remove scripts
    foreach (var script in document.DocumentNode.Descendants("script").ToArray())
    {
        script.Remove();
    }

    // remove styles
    foreach (var style in document.DocumentNode.Descendants("style").ToArray())
    {
        style.Remove();
    }

    // remove comments
    foreach (var style in document.DocumentNode.Descendants("#comment").ToArray())
    {
        style.Remove();
    }

    // sometimes </form> is not removed so we have to remove it manually
    string innerText = (document.DocumentNode.InnerText ?? "").Trim().Replace("</form>", "");

    var sb = new StringBuilder();
    var lines = innerText.Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);
    foreach (var line in lines)
    {
        string trimmed = StringUtils.DecodeAndRemoveSpaces(line);
        if (!string.IsNullOrWhiteSpace(trimmed))
        {
            sb.AppendLine(trimmed);
        }
    }

    var webPage = new WebPage { PageUrl = uri.AbsoluteUri };

    var titleNode = document.DocumentNode.Descendants("title").SingleOrDefault();
    if (titleNode != null)
    {
        webPage.Title = StringUtils.DecodeAndRemoveSpaces(titleNode.InnerText ?? "");
    }

    webPage.Text = sb.ToString();

    return webPage;
}

And the utils class:

public class StringUtils
{
    public static string DecodeAndRemoveSpaces(string text)
    {
        var trimed = HttpUtility.HtmlDecode(text.Trim());
        trimed = trimed.Replace("\t", " ");
        // replace double spaces
        trimed = Regex.Replace(trimed, @"[ ]{2,}", " ");

        return trimed;
    }
}

Usage:

public async Task Test()
{
    using (var client = new HttpClient())
    {
        var uri = new Uri("http://www.google.com");
        string html = await client.GetStringAsync(uri);

        var webPage = ParseHtml(html, uri);
    }
}
2
  • Am I missing something or this will parse the content from a local html file? What about url?
    – David Dury
    Oct 23, 2014 at 13:45
  • You need to get the HTML first. You can use HttpClient.GetStringAsync msdn.microsoft.com/en-us/library/… And then you send this HTML and Uri to ParseHtml method
    – šljaker
    Oct 23, 2014 at 13:53
1

You can send a get request to that URL. Then you can fetch the title, images and content.

You can a see general example here (scroll down to "Example").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.