dimanche 14 septembre 2014

C# + PhantomJS + Google Directions API

        private string googleApiKey = "enter your api key here after activating api";
        internal void StartGoogleAPIScraper()
        {
            string origin = "A";
            string dest = "B";

            while (true)
            {
                this.websiteToDatamine = "https://maps.googleapis.com/maps/api/directions/xml?origin=" + origin + "&destination=" + dest + "&key=" + googleApiKey;

                driver.Navigate().GoToUrl(websiteToDatamine);
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(driver.PageSource);

                string status = xmldoc.SelectSingleNode("DirectionsResponse/status").InnerText;
                if (status == "OK")
                {
                    log("good response from server");
                    XmlNodeList nodelist = xmldoc.SelectNodes("DirectionsResponse/route/leg/step/duration/value");
                    int totalseconds = 0;
                    foreach (XmlNode node in nodelist)
                        totalseconds = totalseconds + Int32.Parse(node.InnerText);
                    log("total seconds = " + totalseconds + " or " + ((double)totalseconds / 60) + " minutes or " + ((double) totalseconds/60/60) + " hours");

                    nodelist = xmldoc.SelectNodes("DirectionsResponse/route/leg/step/distance/value");
                    int totalmeters = 0;
                    foreach (XmlNode node in nodelist)
                        totalmeters = totalmeters + Int32.Parse(node.InnerText);
                    log("total meters = " + totalmeters + " or " + ((double)totalmeters / 1000) + " kilometers");
                }
                else
                {
                    log("bad response from server = " + status);
                }

                System.Threading.Thread.Sleep(1000);
            }
        }