Published on

Getting an Alexa Rank programmatically in C#

Authors
  • avatar
    Name
    Jac Timms
    Twitter

As part of a project I'm working on, I needed to lookup the Alexa Traffic Rank for a domain programmatically. I found the URL the toolbar uses and wrote function to parse the XML and return the value, which I thought I'd share in case it saves someone else 15 minutes of their life…

private int GetAlexaRank(string domain)
{
    var alexaRank = 0;
    try
    {
        var url = string.Format("http://data.alexa.com/data?cli=10&dat=snbamz&url={0}", domain);

        var doc = XDocument.Load(url);

        var rank = doc.Descendants("POPULARITY")
        .Select(node => node.Attribute("TEXT").Value)
        .FirstOrDefault();

        if (!int.TryParse(rank, out alexaRank))
        alexaRank = -1;

    }
    catch (Exception e)
    {
        return -1;
    }

    return alexaRank;
}

You'll need to import System.Xml.Linq