欢迎来到我的的博客园,祝大家学有所成,早点实现自己的人生理想。

使用Selenium+PhantomJS实现网页内容加载(包括网页后期Ajax出来的结果)

一、需求

  需要Nuget下面的库:

  

 

二、代码

class Program
    {
        static void Main(string[] args)
        {
            TestPhantomJsDriver();
             
        }


        private static void TestPhantomJsDriver()
        {
            var service = PhantomJSDriverService.CreateDefaultService();
            service.DiskCache = true;
            service.IgnoreSslErrors = true;
            service.HideCommandPromptWindow = true;
            service.LoadImages = false;
            service.LocalToRemoteUrlAccess = true;
            PhantomJSDriver driver = new PhantomJSDriver(service, new PhantomJSOptions(), TimeSpan.FromSeconds(120));
            var nav = driver.Navigate();
            try
            {
                nav.GoToUrl("http://v.youku.com/v_show/id_XMjc5MTkwNjQ5Ng==.html");
                nav.Refresh();
            }
            catch (Exception e) { Console.WriteLine("refresh exception:" + e.Message); }


            //WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            //try
            //{
            //    var isok = wait.Until(dr => dr.FindElement(By.XPath("span[@id='videoTotalPV']/em")) != null);
            //    var src2 = driver.PageSource;
            //    Console.WriteLine(src == src2);
            //    Console.WriteLine(isok);
            //}
            //catch { }
            var st = driver.TakeScreenshot();
            st.SaveAsFile("d:\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg", ScreenshotImageFormat.Jpeg);

        }

        private static void TestChromeJsDriver()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.HideCommandPromptWindow = true;
            ChromeDriver driver = new ChromeDriver(service, new ChromeOptions() { }, TimeSpan.FromSeconds(120));
      
            var nav = driver.Navigate();
            try
            {
                nav.GoToUrl("http://v.youku.com/v_show/id_XMjc5MTkwNjQ5Ng==.html");
                nav.Refresh();
            }
            catch (Exception e) { Console.WriteLine("refresh exception:" + e.Message); }
            var st = driver.TakeScreenshot();
            st.SaveAsFile("d:\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg", ScreenshotImageFormat.Jpeg);

        }

 

posted @ 2017-06-02 11:09  宋兴柱  阅读(3063)  评论(1编辑  收藏  举报