Get your Google search position in C#
If you want to test your position in Google for a certain search term, you can do so by using the Google website. By position I don't mean Page Rank, but the actual place in the search results. You can also use C# to find the position like the method shows below.
You can use the code to build a cool application that lists the positions of your website based on all your important search terms. You can change it to run asynchronously for better performance when checking multiple search terms.
/// <summary> /// Retrives the position of the url from a search /// on www.oogle.com using the specified search term. /// </summary> public static int GetPosition(Uri url, string searchTerm) { string raw = "http://www.google.com/search?num=39&q={0}&btnG=Search"; string search = string.Format(raw, HttpUtility.UrlEncode(searchTerm)); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII)) { string html = reader.ReadToEnd(); return FindPosition(html, url); } } } /// <summary> /// Examins the search result and retrieves the position. /// </summary> private static int FindPosition(string html, Uri url) { string lookup = "(<h2 class=r><a href=\")(\\w+[a-zA-Z0-9.-?=/]*)"; MatchCollection matches = Regex.Matches(html, lookup); for (int i = 0; i < matches.Count; i++) { string match = matches[i].Groups[2].Value; if (match.Contains(url.Host)) return i + 1; } return 0; }
Examples of use
You simply provide the method with your website URL and the search term to test and it returns the position.
Uri url = new Uri("http://www.example.com"); int position = GetPosition(url, "search term");