Selenium WebDriver使用经验杂记
(一) To Handle Ajax
Selenium WebDriver在加载页面的时候,无论是driver.get(url)或者driver.getPageSource(),会立即返回当时页面的数据。但当代的网页技术都大量使用了异步Ajax调用,这使得许多DOM元素的创建和加载,都分布在页面load结束后的许多零散的时间点,让WebDriver的findElement经常无功而返。这个时候,一般有两种方式来解决问题:
public static String takeScreenshot(WebDriver driver, String savePath, long delay){ try {CommonUtils.waiting(delay * 1000);File screenShotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);String path = "screenshot/"+savePath;if(!savePath.endsWith("/.png"))path = path + ".png";FileUtils.copyFile(screenShotFile, new File(path));LOG.info("Take screenshot at "+savePath);return path;} catch (IOException ex) {LOG.warn("failed to take screenshot for current page, caused by "+ex.getMessage());return null;}}