摘要:是否加載圖片,默認不加載嘗試性解決問題關閉失敗注意和的區別沒打開一個頁面就截圖最大化禁止下載加載圖片嘗試性解決問題關閉失敗滾動窗口。重新調整窗口大小,以適應頁面,需要耗費一定時間。建議等待合理的時間。
import org.openqa.selenium.WebDriver; public interface WebDriverPool { WebDriver get() throws InterruptedException; void returnToPool(WebDriver webDriver); void close(WebDriver webDriver); void shutdown(); }
import java.util.ArrayList; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import net.xby1993.common.util.FileUtil; import org.openqa.selenium.WebDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author taojw */ public class PhantomjsWebDriverPool implements WebDriverPool{ private Logger logger = LoggerFactory.getLogger(getClass()); private int CAPACITY = 5; private AtomicInteger refCount = new AtomicInteger(0); private static final String DRIVER_PHANTOMJS = "phantomjs"; /** * store webDrivers available */ private BlockingDequeinnerQueue = new LinkedBlockingDeque ( CAPACITY); private String PHANTOMJS_PATH; private DesiredCapabilities caps = DesiredCapabilities.phantomjs(); public PhantomjsWebDriverPool() { this(5,false); } /** * * @param poolsize * @param loadImg 是否加載圖片,默認不加載 */ public PhantomjsWebDriverPool(int poolsize,boolean loadImg) { this.CAPACITY = poolsize; innerQueue = new LinkedBlockingDeque (poolsize); PHANTOMJS_PATH = FileUtil.getCommonProp("phantomjs.path"); caps.setJavascriptEnabled(true); caps.setCapability( PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, PHANTOMJS_PATH); // caps.setCapability("takesScreenshot", false); caps.setCapability( PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"); ArrayList cliArgsCap = new ArrayList (); //http://phantomjs.org/api/command-line.html cliArgsCap.add("--web-security=false"); cliArgsCap.add("--ssl-protocol=any"); cliArgsCap.add("--ignore-ssl-errors=true"); if(loadImg){ cliArgsCap.add("--load-images=true"); }else{ cliArgsCap.add("--load-images=false"); } caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap); caps.setCapability( PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_CLI_ARGS, new String[] {"--logLevel=INFO"}); } public WebDriver get() throws InterruptedException { WebDriver poll = innerQueue.poll(); if (poll != null) { return poll; } if (refCount.get() < CAPACITY) { synchronized (innerQueue) { if (refCount.get() < CAPACITY) { WebDriver mDriver = new PhantomJSDriver(caps); // 嘗試性解決:https://github.com/ariya/phantomjs/issues/11526問題 mDriver.manage().timeouts() .pageLoadTimeout(60, TimeUnit.SECONDS); // mDriver.manage().window().setSize(new Dimension(1366, // 768)); innerQueue.add(mDriver); refCount.incrementAndGet(); } } } return innerQueue.take(); } public void returnToPool(WebDriver webDriver) { // webDriver.quit(); // webDriver=null; innerQueue.add(webDriver); } public void close(WebDriver webDriver) { refCount.decrementAndGet(); webDriver.quit(); webDriver = null; } public void shutdown() { try { for (WebDriver driver : innerQueue) { close(driver); } innerQueue.clear(); } catch (Exception e) { // e.printStackTrace(); logger.warn("webdriverpool關閉失敗",e); } } }
import java.util.HashMap; import java.util.Map; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import net.xby1993.common.util.FileUtil; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.DesiredCapabilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChromeWebDriverPool implements WebDriverPool{ private Logger logger = LoggerFactory.getLogger(getClass()); private int CAPACITY = 5; private AtomicInteger refCount = new AtomicInteger(0); private static final String DRIVER_NAME = "chrome"; /** * store webDrivers available */ private BlockingDequeinnerQueue = new LinkedBlockingDeque ( CAPACITY); private static String DRIVER_PATH; private static DesiredCapabilities caps = DesiredCapabilities.chrome(); static { DRIVER_PATH = FileUtil.getCommonProp("chrome.path"); System.setProperty("webdriver.chrome.driver", FileUtil.getCommonProp("chrome.driver.path")); ChromeOptions options = new ChromeOptions(); // options.addExtensions(new File("/path/to/extension.crx")) // options.setBinary(DRIVER_PATH); //注意chrome和chromeDirver的區別 options.addArguments("test-type"); //ignore certificate errors options.addArguments("headless");// headless mode options.addArguments("disable-gpu"); // options.addArguments("log-path=chromedriver.log"); // options.addArguments("screenshot"); 沒打開一個頁面就截圖 //options.addArguments("start-maximized"); 最大化 //Use custom profile Map prefs = new HashMap (); // prefs.put("profile.default_content_settings.popups", 0); //http://stackoverflow.com/questions/28070315/python-disable-images-in-selenium-google-chromedriver prefs.put("profile.managed_default_content_settings.images",2); //禁止下載加載圖片 options.setExperimentalOption("prefs", prefs); caps.setJavascriptEnabled(true); caps.setCapability(ChromeOptions.CAPABILITY, options); // caps.setCapability("takesScreenshot", false); /* Add the WebDriver proxy capability. Proxy proxy = new Proxy(); proxy.setHttpProxy("myhttpproxy:3337"); capabilities.setCapability("proxy", proxy); */ } public ChromeWebDriverPool() { } public ChromeWebDriverPool(int poolsize) { this.CAPACITY = poolsize; innerQueue = new LinkedBlockingDeque (poolsize); } public WebDriver get() throws InterruptedException { WebDriver poll = innerQueue.poll(); if (poll != null) { return poll; } if (refCount.get() < CAPACITY) { synchronized (innerQueue) { if (refCount.get() < CAPACITY) { WebDriver mDriver = new ChromeDriver(caps); // 嘗試性解決:https://github.com/ariya/phantomjs/issues/11526問題 mDriver.manage().timeouts() .pageLoadTimeout(60, TimeUnit.SECONDS); // mDriver.manage().window().setSize(new Dimension(1366, // 768)); innerQueue.add(mDriver); refCount.incrementAndGet(); } } } return innerQueue.take(); } public void returnToPool(WebDriver webDriver) { // webDriver.quit(); // webDriver=null; innerQueue.add(webDriver); } public void close(WebDriver webDriver) { refCount.decrementAndGet(); webDriver.quit(); webDriver = null; } public void shutdown() { try { for (WebDriver driver : innerQueue) { close(driver); } innerQueue.clear(); } catch (Exception e) { // e.printStackTrace(); logger.warn("webdriverpool關閉失敗", e); } } }
import java.io.Closeable; import java.io.IOException; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WebDriverManager implements Closeable{ private static final Logger log=LoggerFactory.getLogger(WebDriverManager.class); private WebDriverPool webDriverPool=null; public WebDriverManager(){ this.webDriverPool=new PhantomjsWebDriverPool(1,false); } public WebDriverManager(WebDriverPool webDriverPool){ this.webDriverPool=webDriverPool; } public void load(String url,int sleepTimeMillis,SeleniumAction... actions){ WebDriver driver=null; try { driver=webDriverPool.get(); driver.get(url); sleep(sleepTimeMillis); WebDriver.Options manage = driver.manage(); manage.window().maximize(); for(SeleniumAction action:actions){ action.execute(driver); } } catch (InterruptedException e) { e.printStackTrace(); log.error("",e); }finally{ if(driver!=null){ webDriverPool.returnToPool(driver); } } } public void load(SeleniumAction... actions){ WebDriver driver=null; try { driver=webDriverPool.get(); WebDriver.Options manage = driver.manage(); manage.window().maximize(); for(SeleniumAction action:actions){ action.execute(driver); } } catch (InterruptedException e) { e.printStackTrace(); log.error("",e); }finally{ if(driver!=null){ webDriverPool.returnToPool(driver); } } } public void shutDown(){ if(webDriverPool!=null){ webDriverPool.shutdown(); } } @Override public void close() throws IOException { shutDown(); } public void sleep(long millis){ try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } }
import org.openqa.selenium.WebDriver; /** * @author taojw * */ public interface SeleniumAction { void execute(WebDriver driver); }
import java.io.File; import java.io.IOException; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; /** * @author taojw * */ public class WindowUtil { /** * 滾動窗口。 * @param driver * @param height */ public static void scroll(WebDriver driver,int height){ ((JavascriptExecutor)driver).executeScript("window.scrollTo(0,"+height+" );"); } /** * 重新調整窗口大小,以適應頁面,需要耗費一定時間。建議等待合理的時間。 * @param driver */ public static void loadAll(WebDriver driver){ Dimension od=driver.manage().window().getSize(); int width=driver.manage().window().getSize().width; //嘗試性解決:https://github.com/ariya/phantomjs/issues/11526問題 driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS); long height=(Long)((JavascriptExecutor)driver).executeScript("return document.body.scrollHeight;"); driver.manage().window().setSize(new Dimension(width, (int)height)); driver.navigate().refresh(); } public static void refresh(WebDriver driver){ driver.navigate().refresh(); } public static void taskScreenShot(WebDriver driver,File saveFile){ if(saveFile.exists()){ saveFile.delete(); } File src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(src, saveFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void changeWindow(WebDriver driver){ // 獲取當前頁面句柄 String handle = driver.getWindowHandle(); // 獲取所有頁面的句柄,并循環判斷不是當前的句柄,就做選取switchTo() for (String handles : driver.getWindowHandles()) { if (handles.equals(handle)) continue; driver.switchTo().window(handles); } } public static void changeWindowTo(WebDriver driver,String handle){ for (String tmp : driver.getWindowHandles()) { if (tmp.equals(handle)){ driver.switchTo().window(handle); break; } } } /** * 打開一個新tab頁,返回該tab頁的windowhandle * @param driver * @param url * @return */ public static String openNewTab(WebDriver driver,String url){ SetstrSet1=driver.getWindowHandles(); ((JavascriptExecutor)driver).executeScript("window.open(""+url+"","_blank");"); sleep(1000); Set strSet2=driver.getWindowHandles(); for(String tmp:strSet2){ if(!strSet1.contains(tmp)){ return tmp; } } return null; } public static void sleep(long millis){ try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 操作關閉模態窗口 * @param driver * @param type 如Id,ClassName * @param sel 選擇器 */ public static void clickModal(WebDriver driver,String type,String sel){ String js="document.getElementsBy"+type+"(""+sel+"")[0].click();"; ((JavascriptExecutor)driver).executeScript(js); } /** * 判斷一個元素是否存在 * @param driver * @param by * @return */ public static boolean checkElementExists(WebDriver driver,By by){ try{ driver.findElement(by); return true; }catch(NoSuchElementException e){ return false; } } /** * 點擊一個元素 * @param driver * @param by */ public static void clickElement(WebDriver driver,By by){ WebElement tmp=driver.findElement(by); Actions actions=new Actions(driver); actions.moveToElement(tmp).click().perform(); } public static void clickElement(WebDriver driver,WebElement tmp){ Actions actions=new Actions(driver); actions.moveToElement(tmp).click().perform(); } public static Object execJs(WebDriver driver,String js){ return ((JavascriptExecutor)driver).executeScript(js); } public static void clickByJsCssSelector(WebDriver driver,String cssSelector){ String js="document.querySelector(""+cssSelector+"").click();"; ((JavascriptExecutor)driver).executeScript(js); } public static Set getCookies(WebDriver driver){ return driver.manage().getCookies(); } public static void setCookies(WebDriver driver,Set cookies){ if(cookies==null){ return; } //Phantomjs存在Cookie設置bug,只能通過js來設置了。 StringBuilder sb=new StringBuilder(); for(Cookie cookie:cookies){ String js="document.cookie=""+cookie.getName()+"="+cookie.getValue()+";path="+cookie.getPath()+";domain="+cookie.getDomain()+"";"; sb.append(js); } ((JavascriptExecutor)driver).executeScript(sb.toString()); } public static String getHttpCookieString(Set cookies){ String httpCookie=""; int index=0; for(Cookie c:cookies){ index++; if(index==cookies.size()){ httpCookie+=c.getName()+"="+c.getValue(); }else{ httpCookie+=c.getName()+"="+c.getValue()+"; "; } } return httpCookie; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/70044.html
摘要:事實上,自動化測試是相對于手動的。減少人為的錯誤自動化測試是機器完成,不存在執行過程中人為的疏忽和錯誤,測試設計完全決定了測試的質量,可以降低減少人為造成的錯誤。而接口自動化測試,主要是對接口進行測試。 今年6月份,由于經濟壓力讓我下定決心進階自動化測試,已經24的我做了3年功能測試,坐標廣...
摘要:一什么是是一個基于瀏覽器的自動化工具,她提供了一種跨平臺跨瀏覽器的端到端的自動化解決方案。模塊主要用來記錄用例執行情況,以便于高效的調查用例失敗信息以及追蹤用例執行情況。測試用例倉庫用例倉庫主要用來組織自動化測試用例。 一、什么是Selenium? Selenium是一個基于瀏覽器的自動化工具,她提供了一種跨平臺、跨瀏覽器的端到端的web自動化解決方案。Selenium主要包括三部分:...
摘要:在這里真心感謝一直在支持我的那幾個粉絲,謝謝你們的持續關注點贊。果然,第三個包也是按的步差來的,而為零不變,也不變。函數里面的話就是個循環咯,當條件不滿足時就一直加,知道條件滿足為止。我每天都會抽時間給我的粉絲解答,給與一些學習資源。 目錄 前言 準備工作 分析(x0) 分析(x1) 分析(...
摘要:然而,市面上的測試工具范圍太廣了,很難做出選擇。這篇熱門文章將會選出最受歡迎的測試工具并且它已經被更新過以便反映出年的工具狀態。是一個根據規范創建的驗收測試框架。 為了傳播有質量的代碼, 我們必須在編碼時有測試的觀念 (如果不是在做 TDD)。 然而,市面上的PHP測試工具范圍太廣了,很難做出選擇。 這篇熱門文章將會選出最受歡迎的測試工具并且它已經被更新過以便反映出2017年的 QA...
摘要:時間永遠都過得那么快,一晃從年注冊,到現在已經過去了年那些被我藏在收藏夾吃灰的文章,已經太多了,是時候把他們整理一下了。那是因為收藏夾太亂,橡皮擦給設置私密了,不收拾不好看呀。 ...
閱讀 2628·2021-11-19 09:56
閱讀 874·2021-09-24 10:25
閱讀 1632·2021-09-09 09:34
閱讀 2195·2021-09-09 09:33
閱讀 1052·2019-08-30 15:54
閱讀 542·2019-08-29 18:33
閱讀 1264·2019-08-29 17:19
閱讀 505·2019-08-29 14:19