Selenium獲得當前頁面的URL

    /**
         * getCurrentURL:(get the current page URL address). 

         * @author huchan
         * @param driver  --- the web driver instance
         * @return String ---the url of current page
         * @since JDK 1.6
         */
        public String getCurrentPageURL(){
            String pageurl="";
            JavascriptExecutor je=(JavascriptExecutor) driver;
            final String docstate=(String) je.executeScript("return document.readyState");
            logger.info("Current loading page state is:"+docstate);
            WebDriverWait wait=new WebDriverWait(driver,120);
            ExpectedCondition<Boolean> ec = new ExpectedCondition<Boolean>() {
                  @Override
                public Boolean apply(WebDriver d) {
                    return (docstate.equals("complete"));
                  }
                };
            try{
               logger.info("We just wait for the current page load correctly now...");
               wait.until(ec);           
               pageurl=driver.getCurrentUrl();
               logger.info("we found the current url is:"+pageurl);
            }
            catch(TimeoutException e){
                pageurl="time out:120 seconds";
                logger.error("Sorry the page cannot be loaded correctly:"+e.getMessage()+driver.getCurrentUrl());
            }
            return pageurl;
        }

很少說,代碼如上。關鍵點是必定要等待頁面加載完成了再使用driver.getCurrentUrl()方法,不然的話可能獲得的頁面URL 不正確。web


做者:高級測試開發網
本文版權歸做者全部,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利。
相關文章
相關標籤/搜索