本文将为您提供关于如何在不清除cookie或缓存的情况下启动SeleniumRemoteWebDriver或WebDriver?的详细介绍,我们还将为您解释开启清除内存不被使用的动态链接文件此项功能的
本文将为您提供关于如何在不清除cookie或缓存的情况下启动Selenium RemoteWebDriver或WebDriver?的详细介绍,我们还将为您解释开启清除内存不被使用的动态链接文件此项功能的相关知识,同时,我们还将为您提供关于Java Selenium封装--RemoteWebDriver、java – 如何用selenium webdriver发送cookies?、JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测、org.openqa.selenium.remote.RemoteWebDriver的实例源码的实用信息。
本文目录一览:- 如何在不清除cookie或缓存的情况下启动Selenium RemoteWebDriver或WebDriver?(开启清除内存不被使用的动态链接文件此项功能)
- Java Selenium封装--RemoteWebDriver
- java – 如何用selenium webdriver发送cookies?
- JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测
- org.openqa.selenium.remote.RemoteWebDriver的实例源码
如何在不清除cookie或缓存的情况下启动Selenium RemoteWebDriver或WebDriver?(开启清除内存不被使用的动态链接文件此项功能)
用例:使用用户名登录,导航到第二因素认证页面以执行多项操作(即回答基于知识的问题),然后导航至最后一页以输入密码。关闭浏览器,然后尝试使用用户名再次登录。这次绕过了第二因素身份验证页面,因为该应用程序识别出cookie,并提示用户直接输入密码。
问题:我正在使用Selenium
RemoteWebDriver在单独的测试计算机上运行这些测试,并且当我关闭第一个浏览器并打开一个新的RemoteWebDriver实例时,它似乎首先清除Cookie和缓存,并且每次我打开第二个身份验证页面尝试登录。
我需要什么:帮助弄清楚如何创建RemoteWebDriver的新实例,而又不会自动清除任何cookie或缓存,因此将绕过第二个因素身份验证页面。我需要IE,Chrome,Firefox和Safari浏览器。
我没有任何代码可以明确清除此代码,但是我也没有任何尝试将其清除的代码(如果存在的话)。我没有尝试过太多其他事情,因为我不知道尝试什么。
版本:Selenium WebDriver:2.45.0.0,Selenium Grid:2.45.0
谢谢!
答案1
小编典典在Firefox上保留cookie;创建一个自定义配置文件(请参阅此处的示例),并在每次启动新的RemoteWebDriver实例时使用它。这样,Firefox将在会话之间的所有现有cookie中重用相同的配置文件。但是,这不会保存测试本身收到的cookie。请参阅下面的替代方法以获取解决方案。
类似的方法适用于Chrome-
link。
对于Internet
Explorer(而不是自定义配置文件),需要确保将CleanCleanSession功能设置为false,以防止在会话启动链接上清除cookie
。
替代解决方案 :Cookies也可以在测试本身中进行操作:
- 测试结束时获取所有cookie:
ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies;
将它们存放在某个地方。如何执行取决于自动化设置,但是通常简单地序列化到磁盘应该可以正常工作。
在测试开始时反序列化cookie并通过WebDriver添加它们:
foreach (var cookie in cookies) driver.Manage().Cookies.AddCookie(cookie);
Java Selenium封装--RemoteWebDriver
package com.selenium.driver;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Cookie;
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.remote.Augmenter;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.RemoteWebElement;
public class JSWebDriver{
private RemoteWebDriver wd = null;
private JavascriptExecutor jse = null;
public JSWebDriver(URL remoteAddress, Capabilities desiredCapabilities) {
wd = new RemoteWebDriver(remoteAddress, desiredCapabilities);
}
///
///浏览器url导航
///
public void goTo(String url){
wd.get(url);
}
///
///浏览器退出
///
public void quit(){
wd.quit();
}
///
///浏览器后退
///
public void back(){
wd.navigate().back();
}
///
///浏览器前进
///
public void forward(){
wd.navigate().forward();
}
///
///浏览器刷新
///
public void refresh(){
wd.navigate().refresh();
}
///
///切换到新浏览器窗口;按照title、url、index;支持正则匹配
///
public void switchToWindow(String by, String value, String...match) throws Exception{
String currenthandle = wd.getWindowHandle();
Set<String> handles = wd.getWindowHandles();
int currentIndex = -1;
String searchString = "";
for(String handle : handles){
currentIndex += 1;
if(handle.equals(currenthandle)){
continue;
}else{
wd.switchTo().window(handle);
if (match.length == 1 && match[0].equals("regex")){
if (by.equals("title")){
searchString = wd.getTitle();
}else if (by.equals("url")){
searchString = wd.getCurrentUrl();
}
Pattern pattern = Pattern.compile(value);
Matcher matcher = pattern.matcher(searchString);
if(matcher.find()){
return;
}
}else{
if (by.equals("title")){
searchString = wd.getTitle();
}else if (by.equals("url")){
searchString = wd.getCurrentUrl();
}else if (by.equals("index")){
searchString = Integer.toString(currentIndex);
}
if(searchString.equals(value)){
return;
}
}
}
}
Exception e = new Exception("Swtich Window Failed, Please Make Sure The Locator Was Right.");
throw e;
}
///
///JS弹框确认
///
public void clickAlertSure(){
Alert alert = wd.switchTo().alert();
alert.accept();
}
///
///JS弹框取消
///
public void clickAlertDismiss()
{
Alert alert = wd.switchTo().alert();
alert.dismiss();
}
///
///设置prompt弹框内容
///
public void setPromptMessage(String parameter){
Alert alert = wd.switchTo().alert();
alert.sendKeys(parameter);
}
///
///获取JS弹框内容
///
public String getPromptMessage(){
Alert alert = wd.switchTo().alert();
return alert.getText();
}
///
///切换到Frame窗口;先定位到iframe元素
///
public void switchToFrame(JSWebElement jselement){
wd.switchTo().frame(jselement.getNativeWebElement());
}
///
///执行JS脚本
///
public void executeScript(String parameter){
JavascriptExecutor js = getJSE();
js.executeScript(parameter);
}
///
///获取指定cookie
///
public String getCookie(String name){
Cookie cookie=wd.manage().getCookieNamed(name);
if (cookie == null){ return "null"; }
return cookie.getValue();
}
///
///获取所有cookie
///
public Map<String, String> getCookies(){
Map<String, String> newCookies = new HashMap<String, String>();
Set<Cookie> cookies= wd.manage().getCookies();
for (Cookie cookie : cookies){
newCookies.put(cookie.getName(), cookie.getValue());
}
return newCookies;
}
///
///截取屏幕
///
public void getScreen(String filepath){
WebDriver augmentedDriver = new Augmenter().augment(this.wd);
TakesScreenshot ts = (TakesScreenshot) augmentedDriver;
File screenShotFile = ts.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile (screenShotFile, new File(filepath));
}catch (IOException e){
e.printStackTrace();
}
}
///
///获取title
///
public String getTitle(){
return wd.getTitle();
}
///
///获取url
///
public String getUrl(){
return wd.getCurrentUrl();
}
///
///获取HTML源码
///
public String getSource(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return wd.getPageSource();
}
///
///滚动页面到指定位置
///
public void scroll(String x, String y){
if (x.equals("left")){
x = "0";
}else if (x.equals("right")){
x = "document.body.scrollWidth";
}else if (x.equals("middle")){
x = "document.body.scrollWidth/2";
}
if (y.equals("top")){
y = "0";
}else if (y.equals("buttom")){
y = "document.body.scrollHeight";
}else if (y.equals("middle")){
y = "document.body.scrollHeight/2";
}
this.executeScript(String.format("scroll(%s,%s);", x, y));
}
///
///最大化浏览器
///
public void maximize(){
wd.manage().window().maximize();
}
public JSWebElement findElementById(String using) {
try {
return new JSWebElement((RemoteWebElement)wd.findElementById(using));
}catch (NoSuchElementException e){
return new JSWebElement();
}
}
public JSWebElement findElementByCssSelector(String using) {
try {
return new JSWebElement((RemoteWebElement)wd.findElementByCssSelector(using));
}catch (NoSuchElementException e){
return new JSWebElement();
}
}
public JSWebElement findElementByXPath(String using) {
try {
return new JSWebElement((RemoteWebElement)wd.findElementByXPath(using));
}catch (NoSuchElementException e){
return new JSWebElement();
}
}
public JSWebElement findElementByLinkText(String using) {
try {
return new JSWebElement((RemoteWebElement)wd.findElementByLinkText(using));
}catch (NoSuchElementException e){
return new JSWebElement();
}
}
public JSWebElement findElementByDom(String using) {
try {
JavascriptExecutor js = this.getJSE();
WebElement we = (WebElement)js.executeScript(String.format("return %s", using));
return new JSWebElement((RemoteWebElement)we);
}catch (NoSuchElementException e){
return new JSWebElement();
}
}
///
///获取原生的RemoteWebdriver对象
///
public RemoteWebDriver getNativeWebDriver(){
return this.wd;
}
private JavascriptExecutor getJSE(){
if (this.jse == null){
this.jse = (JavascriptExecutor) this.wd;
}
return jse;
}
}
java – 如何用selenium webdriver发送cookies?
如何通过登录操作?
使用Chrome和Firefox驱动,使用java语言.
解决方法
Cookie ck = new Cookie("name","value"); driver.manage().addCookie(ck);
使用Python API创建Cookie如下:
driver.add_cookie({'name': 'foo','value': 'bar'})
JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测
我正在尝试使用selenium和铬在网站中自动化一个非常基本的任务,但是以某种方式网站会检测到铬是由selenium驱动的,并阻止每个请求。我怀疑该网站是否依赖像这样的公开DOM变量https://stackoverflow.com/a/41904453/648236来检测selenium驱动的浏览器。
我的问题是,有没有办法使navigator.webdriver标志为假?我愿意尝试修改后重新尝试编译selenium源,但是似乎无法在存储库中的任何地方找到NavigatorAutomationInformation源https://github.com/SeleniumHQ/selenium
任何帮助深表感谢
PS:我还从https://w3c.github.io/webdriver/#interface尝试了以下操作
Object.defineProperty(navigator, ''webdriver'', { get: () => false, });
但是它仅在初始页面加载后更新属性。我认为网站会在执行脚本之前检测到变量。
答案1
小编典典从当前的实现开始,一种理想的访问网页而不被检测到的方法是使用ChromeOptions()该类向以下参数添加几个参数:
排除enable-automation
开关的集合
关掉 useAutomationExtension
通过以下实例ChromeOptions
:
Java示例:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");ChromeOptions options = new ChromeOptions();options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));options.setExperimentalOption("useAutomationExtension", false);WebDriver driver = new ChromeDriver(options);driver.get("https://www.google.com/");
Python范例
from selenium import webdriveroptions = webdriver.ChromeOptions()options.add_experimental_option("excludeSwitches", ["enable-automation"])options.add_experimental_option(''useAutomationExtension'', False)driver = webdriver.Chrome(options=options, executable_path=r''C:\path\to\chromedriver.exe'')driver.get("https://www.google.com/")
org.openqa.selenium.remote.RemoteWebDriver的实例源码
public static WebDriver getFirefoxDriver() throws Exception { baseDir = new File(".").getPath(); System.out.println("******** " + baseDir); String path = "src/test/resources/geckodriver"; System.out.println("******** " + path); System.setProperty("webdriver.gecko.driver",path); DesiredCapabilities capabilities = DesiredCapabilities.firefox(); capabilities.setCapability("marionette",true); capabilities.setCapability("networkConnectionEnabled",true); capabilities.setCapability("browserConnectionEnabled",true); WebDriver driver = new RemoteWebDriver( new URL("http://localhost:4444"),capabilities); // WebDriver driver = new MarionetteDriver(capabilities); return driver; }
public static final String download(RemoteWebDriver driver,String url) { String folder = DOWNLOAD_PATH + RandomStringUtils.randomAlphabetic(10); new File(folder).mkdirs(); Map<String,String> headers = new HashMap<String,String>(); headers.put("Cookie",getCookie(driver)); byte[] data = HttpUtils.get(url,headers); try { String filename; String contentdisposition = headers.get("Content-disposition"); if (StringUtils.contains(contentdisposition,"=")) { filename = contentdisposition.substring(contentdisposition.indexOf("=") + 1); } else { filename = new URL(url).getPath(); if (filename.contains("/")) { filename = filename.substring(filename.lastIndexOf("/") + 1); } } IoUtils.write(data,new FileOutputStream(folder + "/" + filename)); return folder + "/" + filename; } catch (Exception e) { throw new RuntimeException("Download Failed!",e); } }
@Test public void testDriver() throws IOException { WebDriver driver = new RemoteWebDriver(toUrl("http://localhost:9515"),DesiredCapabilities.chrome()); driver.get(URL2); String response = driver.getPageSource(); Document doc = Jsoup.connect(URL2).ignoreContentType(true).get(); Elements scriptTags = doc.select("body"); // get All functions try { String result = (String) engine.eval(response); } catch (ScriptException e) { e.printstacktrace(); } log.info("PageSource " + response); driver.quit(); }
@Test public void shouldCreateRemoteDriverInstance() throws MalformedURLException { XmlConfig config = new XmlConfig(new HashMap<String,String>() { { put(broWSER_NAME,"firefox"); put(PLATFORM_NAME,"ANY"); put(TEST_NAME,"shouldCreateRemoteDriverInstance"); } }); WebDriver driver = mock(RemoteWebDriver.class,RETURNS_DEEP_STUBS); WebDriverProvider spyFactory = spy(defaultFactory); Reflect spyReflectedDriver = spy(spyFactory.wrapDriver(firefox)); doReturn(spyReflectedDriver).when(spyFactory).wrapDriver(firefox); doReturn(on(driver)).when(spyReflectedDriver).create(new URL(firefox.url()),firefox.configuration(config)); assertthat(spyFactory.createDriver(firefox,config)).isinstanceOf(RemoteWebDriver.class); }
@Before public void startApp() throws Exception { DesiredCapabilities capabilities = new DesiredCapabilities(); Map<String,Object> baseState = new HashMap<>(); baseState.put("type","NATIVE"); baseState.put("executable",APP); baseState.put("locator","//Window"); capabilities.setCapability("appdriver-basestate",baseState); Map<String,Object> options = new HashMap<>(); options.put("cloSEOnQuit",true); capabilities.setCapability("appdriver-options",options); driver = new RemoteWebDriver(new URL("http://localhost:8080"),capabilities); }
@Before public void startApp() throws Exception { DesiredCapabilities capabilities = new DesiredCapabilities(); Map<String,"//WPFWindow"); capabilities.setCapability("appdriver-basestate",capabilities); }
protected PageObject(RemoteWebDriver driver,String title,String urlTail) { this.driver = driver; this.title = title; this.urlRoot = "http://localhost:8080"; this.urlTail = urlTail; this.url = urlRoot + urlTail; String message = String.format( "Expected to be on page with" + "title containing %s and" + "url containing %s but" + "title was %s and" + "url was %s",title,url,driver.getTitle(),driver.getcurrenturl()); assertTrue(message,isCurrentPage()); }
private static WebDriver createRemoteDriver(String url,DesiredCapabilities caps,Boolean checkForProxy,Properties props) { try { if (isAppiumNative(url,caps.asMap())) { if (isAndroidNative(caps.asMap())) { return new io.appium.java_client.android.AndroidDriver(new URL(url),caps); } else if (isIOSNative(caps.asMap())) { return new io.appium.java_client.ios.IOSDriver(new URL(url),caps); } } if (url == null) { return new RemoteWebDriver(caps); } if (checkForProxy) { return new RemoteWebDriver(RemoteProxy.getProxyExecutor(new URL(url),props),caps); } return new RemoteWebDriver(new URL(url),caps); } catch (MalformedURLException ex) { LOGGER.log(Level.SEVERE,ex.getMessage(),ex); } return null; }
@Test public void testTokenPaymentWithout3DS() throws ParseException,PaymentException,InterruptedException { Token token = mpay24.token(getTestTokenRequest(null)); assertEquals("REDIRECT",token.getReturnCode()); assertNotNull(token.getApiKey()); assertNotNull(token.getRedirectLocation()); assertNotNull(token.getToken()); RemoteWebDriver driver = openFirefoxAtUrl(token.getRedirectLocation()); driver.findElement(By.name("cardnumber")).sendKeys("4444333322221111"); driver.findElement(By.name("cardnumber")).sendKeys(Keys.TAB); driver.findElement(By.id("expiry")).sendKeys("0520"); driver.findElement(By.id("expiry")).sendKeys(Keys.TAB); driver.findElement(By.name("cvc")).sendKeys("123"); driver.findElement(By.name("cvc")).sendKeys(Keys.TAB); TimeUnit.SECONDS.sleep(1l); Payment response = mpay24.payment(getTestPaymentRequest(),getTokenPaymentType(token.getToken())); assertEquals("OK",response.getReturnCode()); assertNotNull(response.getmPayTid()); }
@Test public void testShoppingCartAmounts() throws PaymentException { Payment response = mpay24.paymentPage(getTestPaymentRequest(120.0,null),getTestShoppingCart()); assertSuccessfullResponse(response); RemoteWebDriver driver = openFirefoxAtUrl(response.getRedirectLocation()); WebElement element = driver.findElementById("cart"); assertEquals("Rabatt:",element.findElement(By.xpath("tfoot/tr[1]/th")).getText()); assertEquals("-10,00",element.findElement(By.xpath("tfoot/tr[1]/td")).getText()); assertEquals("Versandkosten:",element.findElement(By.xpath("tfoot/tr[2]/th")).getText()); assertEquals("-5,element.findElement(By.xpath("tfoot/tr[2]/td")).getText()); assertEquals("Zwischensumme:",element.findElement(By.xpath("tfoot/tr[3]/th")).getText()); assertEquals("100,element.findElement(By.xpath("tfoot/tr[3]/td")).getText()); assertEquals("20.00% USt.:",element.findElement(By.xpath("tfoot/tr[4]/th")).getText()); assertEquals("20,element.findElement(By.xpath("tfoot/tr[4]/td")).getText()); assertEquals("Gesamtpreis:",element.findElement(By.xpath("tfoot/tr[5]/th")).getText()); assertEquals("EUR 120,element.findElement(By.xpath("tfoot/tr[5]/td")).getText()); }
@Test public void testLanguageEnglish() throws PaymentException { Payment response = mpay24.paymentPage(getTestPaymentRequest(1.0,null,Language.EN),getTestShoppingCart(getTestShoppingCartItemList())); assertSuccessfullResponse(response); RemoteWebDriver driver = openFirefoxAtUrl(response.getRedirectLocation()); WebElement element = driver.findElementById("cart"); assertEquals("No.",element.findElement(By.xpath("thead/tr[1]/th[1]")).getText()); assertEquals("Prod. No.",element.findElement(By.xpath("thead/tr[1]/th[2]")).getText()); assertEquals("Product Name",element.findElement(By.xpath("thead/tr[1]/th[3]")).getText()); assertEquals("Amount ordered",element.findElement(By.xpath("thead/tr[1]/th[4]")).getText()); assertEquals("Price/Item",element.findElement(By.xpath("thead/tr[1]/th[5]")).getText()); assertEquals("Total",element.findElement(By.xpath("thead/tr[1]/th[6]")).getText()); assertEquals("discount:",element.findElement(By.xpath("tfoot/tr[1]/th")).getText()); assertEquals("Shipping Costs:",element.findElement(By.xpath("tfoot/tr[2]/th")).getText()); assertEquals("Subtotal:",element.findElement(By.xpath("tfoot/tr[3]/th")).getText()); assertEquals("Order Total:",element.findElement(By.xpath("tfoot/tr[5]/th")).getText()); }
@Test public void testShippingAddress() throws PaymentException { Payment response = mpay24.paymentPage(getTestPaymentRequest(),getCustomerWithAddress(null)); assertSuccessfullResponse(response); RemoteWebDriver driver = openFirefoxAtUrl(response.getRedirectLocation()); driver.findElement(By.name("selCC|VISA")).click(); webdriverwait wait = new webdriverwait(driver,20); wait.until(ExpectedConditions.elementToBeClickable(By.id("cardnumber"))); assertEquals("Testperson-de Approved",driver.findElement(By.name("BillingAddr/Name")).getAttribute("value")); assertEquals("Hellersbergstraße 14",driver.findElement(By.name("BillingAddr/Street")).getAttribute("value")); assertNotExistent(driver,By.name("BillingAddr/Street2")); assertEquals("41460",driver.findElement(By.name("BillingAddr/Zip")).getAttribute("value")); assertEquals("Neuss",driver.findElement(By.name("BillingAddr/City")).getAttribute("value")); assertEquals("Ankeborg",driver.findElement(By.name("BillingAddr/State")).getAttribute("value")); assertEquals("Deutschland",driver.findElement(By.name("BillingAddr/Country/@Code")).findElement(By.xpath("option[@selected='']")).getText()); }
@Test public void testShippingAddressWithStreet2() throws PaymentException { Payment response = mpay24.paymentPage(getTestPaymentRequest(),getCustomerWithAddress("Coconut 3")); assertSuccessfullResponse(response); RemoteWebDriver driver = openFirefoxAtUrl(response.getRedirectLocation()); driver.findElement(By.name("selPAYPAL|PAYPAL")).click(); webdriverwait wait = new webdriverwait(driver,20); wait.until(ExpectedConditions.elementToBeClickable(By.name("BillingAddr/Street"))); assertEquals("Testperson-de Approved",driver.findElement(By.name("BillingAddr/Street")).getAttribute("value")); assertEquals("Coconut 3",driver.findElement(By.name("BillingAddr/Street2")).getAttribute("value")); assertEquals("41460",driver.findElement(By.name("BillingAddr/Country/@Code")).findElement(By.xpath("option[@selected='']")).getText()); }
public SeleniumExtension() { handlerMap.put(ChromeDriver.class,ChromeDriverHandler.class); handlerMap.put(FirefoxDriver.class,FirefoxDriverHandler.class); handlerMap.put(EdgeDriver.class,EdgeDriverHandler.class); handlerMap.put(OperaDriver.class,OperaDriverHandler.class); handlerMap.put(SafariDriver.class,SafariDriverHandler.class); handlerMap.put(RemoteWebDriver.class,RemoteDriverHandler.class); handlerMap.put(AppiumDriver.class,AppiumDriverHandler.class); handlerMap.put(List.class,ListDriverHandler.class); handlerMap.put(PhantomJSDriver.class,OtherDriverHandler.class); templateHandlerMap.put("chrome",ChromeDriver.class); templateHandlerMap.put("firefox",FirefoxDriver.class); templateHandlerMap.put("edge",EdgeDriver.class); templateHandlerMap.put("opera",OperaDriver.class); templateHandlerMap.put("safari",SafariDriver.class); templateHandlerMap.put("appium",AppiumDriver.class); templateHandlerMap.put("phantomjs",PhantomJSDriver.class); templateHandlerMap.put("chrome-in-docker",RemoteWebDriver.class); templateHandlerMap.put("firefox-in-docker",RemoteWebDriver.class); templateHandlerMap.put("opera-in-docker",RemoteWebDriver.class); }
/** * Initialises the WebDriver (client). * * This method should be called once before each test to ensure that the session state doesn't bleed from one test * to another (such as user being logged in). */ public void initialise() { final ChromeOptions chromeOptions = new ChromeOptions(); final Map<String,Object> chromePrefs = new HashMap<>(); log.info("Setting WebDriver download directory to '{}'.",downloadDirectory); chromePrefs.put("download.default_directory",downloadDirectory.toAbsolutePath().toString()); chromeOptions.setExperimentalOption("prefs",chromePrefs); log.info("Configuring WebDriver to run in {} mode.",isHeadlessMode ? "headless" : "full,graphical"); if (isHeadlessMode) { chromeOptions.addArguments("--headless"); chromeOptions.addArguments("window-size=1920,1080"); } webDriver = new RemoteWebDriver(webDriverServiceProvider.getUrl(),chromeOptions); }
@Override public <X> X getScreenshotAs(OutputType<X> target) { if (getWebDriver().getClass() == RemoteWebDriver.class) { WebDriver augmentedDriver = new Augmenter().augment(getWebDriver()); return ((TakesScreenshot) augmentedDriver).getScreenshotAs(target); } else { return ((TakesScreenshot) getWebDriver()).getScreenshotAs(target); } }
@Override public <X> X getScreenshotAs(final OutputType<X> target) throws WebDriverException { if (driver.getClass() == RemoteWebDriver.class) { WebDriver augmentedDriver = new Augmenter().augment(driver); return ((TakesScreenshot) augmentedDriver).getScreenshotAs(target); } else { return ((TakesScreenshot) driver).getScreenshotAs(target); } }
@Test @NeedRestartDriver public void chrome_config_test() { openPage("main.html",BasePage.class); WebDriver webDriver = ((FramesTransparentWebDriver) SeleniumHolder.getWebDriver()).getWrappedDriver(); Assert.assertTrue(webDriver instanceof ChromeDriver); Assert.assertEquals(((RemoteWebDriver) webDriver).getCapabilities().getCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIoUR),UnexpecteDalertBehavIoUr.IGnorE.toString()); }
/** * A helper method that enriches a {@link RemoteWebDriver} instance with the ability to route all browser * interaction requests directly to the node on which the session was created and route only the session termination * request to the hub. * * @param driver - A {@link RemoteWebDriver} instance. * @param hub - A {@link Host} object that represents the Hub information. * @return - A {@link RemoteWebDriver} instance that is enriched with the ability to route all browser interactions * directly to the node. */ public static RemoteWebDriver enrichRemoteWebDriverToInteractDirectlyWithNode(RemoteWebDriver driver,Host hub) { if (hub == null) { return driver; } try { CommandExecutor grid = driver.getCommandExecutor(); String sessionId = driver.getSessionId().toString(); GridApiAssistant assistant = new GridApiAssistant(hub); Host nodeHost = assistant.getNodeDetailsForSession(sessionId); URL url = new URL(String.format("http://%s:%d/wd/hub",nodeHost.getIpAddress(),nodeHost.getPort())); CommandExecutor node = new HttpCommandExecutor(url); CommandCodec commandCodec = getCodec(grid,"commandCodec"); ResponseCodec responseCodec = getCodec(grid,"responseCodec"); setCodec(node,commandCodec,"commandCodec"); setCodec(node,responseCodec,"responseCodec"); appendListenerToWebDriver(driver,grid,node); LOG.info("Traffic will Now be routed directly to the node."); LOG.warning(constructWarningMessage(hub)); } catch (Exception e) { //Gobble exceptions LOG.warning("Unable to enrich the RemoteWebDriver instance. Root cause :" + e.getMessage() + ". Returning back the original instance that was passed,as is."); } return driver; }
private static Host getHubInfo(RemoteWebDriver driver) { Host hub = null; CommandExecutor executor = driver.getCommandExecutor(); if (executor instanceof HttpCommandExecutor) { URL url = ((HttpCommandExecutor) executor).getAddressOfRemoteServer(); hub = new Host(url.getHost(),Integer.toString(url.getPort())); } return hub; }
@SuppressWarnings("unchecked") private static void appendListenerToWebDriver(RemoteWebDriver rwd,CommandExecutor grid,CommandExecutor node) throws NoSuchMethodException,InvocationTargetException,illegalaccessexception { CommandExecutor executor = new CustomCommandExecutor(grid,node); Class clazz = rwd.getClass(); while (!RemoteWebDriver.class.equals(clazz)) { clazz = clazz.getSuperclass(); } Method m = clazz.getDeclaredMethod("setCommandExecutor",CommandExecutor.class); m.setAccessible(true); m.invoke(rwd,executor); }
/** * Get the Selenium driver for the specified test class instance. * * @return driver object (may be 'null') */ public static WebDriver getDriver() { SeleniumConfig config = SeleniumConfig.getConfig(); GridServerParms hubParms = GridServerParms.getHubParms(config); if (isHubActive()) { return new RemoteWebDriver(hubParms.endpointUrl,config.getbrowserCaps()); } else { throw new IllegalStateException("No Selenium Grid instance was found at " + hubParms.endpointUrl); } }
@Test public void testDeveloperTab() throws InterruptedException { RemoteWebDriver driver = chrome.getWebDriver(); driver.get("http://gittalentbackend:8080/githubimport/developer/ldoguin"); driver.get("http://gittalentbackend:8080/githubimport/status"); while(driver.getPageSource().contains("false")) { Thread.sleep(1000); driver.navigate().refresh(); }; driver.get("http://gittalentfrontend/"); WebElement myDynamicElement = (new webdriverwait(driver,20)) .until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/app-root/div/developers/div[1]/div[2]/div[1]/table/tbody/tr/td[2]"))); Assert.assertTrue(myDynamicElement.getText().equals("ldoguin")); }
public static MobileApp getInstance() throws Throwable { if (ourInstance == null) { ourInstance = new MobileApp(); System.out.println("**********************Session id created********************** new session id : "+((RemoteWebDriver) driver.get()).getSessionId()); } if(ourInstance != null && ((RemoteWebDriver) driver.get()).getSessionId() == null){ ourInstance = new MobileApp(); System.out.println("**********************Session id killed and new session created********************** new session id : "+((RemoteWebDriver) driver.get()).getSessionId()); } return ourInstance; }
public void succeedsWhenRequestingNonNativeEventsCapability() throws Throwable { DesiredCapabilities caps = new DesiredCapabilities("java","1.0",Platform.getCurrent()); caps.setCapability("nativeEvents",false); driver = new JavaDriver(caps,caps); Capabilities capabilities = ((RemoteWebDriver) driver).getCapabilities(); AssertJUnit.assertTrue(!capabilities.is("nativeEvents")); }
public void getSessions() { driver = new JavaDriver(); JavaDriver driver1 = new JavaDriver(); SessionId id1 = ((RemoteWebDriver) driver).getSessionId(); SessionId id2 = driver1.getSessionId(); AssertJUnit.assertFalse(id1.equals(id2)); }
public void javaDriver() { driver = new JavaDriver(); Capabilities capabilities = ((RemoteWebDriver) driver).getCapabilities(); AssertJUnit.assertEquals("java",capabilities.getbrowserName()); AssertJUnit.assertEquals(true,capabilities.is("takesScreenshot")); AssertJUnit.assertEquals(false,capabilities.is("nativeEvents")); }
private void injectSessionId(final ITestResult testResult) { ofNullable(DRIVER_CONTAINER.get()) .map(t -> t._1) .filter(d -> d instanceof RemoteWebDriver) .map(d -> ((RemoteWebDriver) d).getSessionId()) .ifPresent(id -> testResult.setAttribute("sessionId",id)); }
@Override public WebDriver createDriver(final browser browser,final XmlConfig config) { final RemoteWebDriver driver = mock(RemoteWebDriver.class); when(driver.getScreenshotAs(OutputType.BYTES)).thenReturn(new byte[]{1,2,3}); doReturn(new SessionId(randomAlphanumeric(14))).when(driver).getSessionId(); return driver; }
private void instantiateWebDriver( DesiredCapabilities desiredCapabilities ) throws MalformedURLException { System.out.println( String.format( "Current Operating System : {%s}",operatingSystem ) ); System.out.println( String.format( "Current System Architecture : {%s}",systemArchitecture ) ); System.out.println( String.format( "Current browser : {%s}\n",driverType ) ); if( useRemoteWebDriver ) { URL seleniumGridURL = new URL( System.getProperty( "gridURL" ) ); System.out.println( "seleniumGridURL = " + seleniumGridURL ); String desiredbrowserVersion = System.getProperty( "desiredbrowserVersion" ); String desiredplatform = System.getProperty( "desiredplatform" ); if( ( null != desiredplatform ) && desiredplatform.isEmpty() ) { desiredCapabilities.setPlatform( Platform.valueOf( desiredplatform ) ); } if( null != desiredbrowserVersion && desiredbrowserVersion.isEmpty() ) { desiredCapabilities.setVersion( desiredbrowserVersion ); } driver = new RemoteWebDriver( seleniumGridURL,desiredCapabilities ); } else { driver = selectedDriverType.getWebDriverObject( desiredCapabilities ); } }
/** * 兼容循环执行时 不会重新加载构造方法的问题 * * @return */ public RemoteWebDriver getDriver() { if (driver == null || driver.getSessionId() == null) { driver = DriverFactory.getInstance().getDriver(); wait = new webdriverwait(driver,DRIVER_WAIT_TIMEOUT_IN_SECOND,500); } return driver; }
@Before public void startApp() throws Exception { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("app",APP); driver = new RemoteWebDriver(new URL("http://localhost:8080"),capabilities); }
@Before public void startApp() throws Exception { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("app",capabilities); driver.manage().timeouts().implicitlyWait(17,TimeUnit.SECONDS); String windowHandle = driver.getwindowHandle(); assertNotNull(windowHandle); Point windowPosition = driver.manage().window().getPosition(); assertNotNull(windowPosition); }
private void initQueryObject() { Capabilities mockedCapabilities = mock(Capabilities.class); when(mockedCapabilities.getbrowserName()).thenReturn(browserType.GOOGLECHROME); when(mockedCapabilities.getPlatform()).thenReturn(Platform.YOSEMITE); RemoteWebDriver mockedWebDriver = mock(RemoteWebDriver.class); when(mockedWebDriver.getCapabilities()).thenReturn(mockedCapabilities); when(mockedWebDriver.findElement(DEFAULT_LOCATOR)).thenReturn(MOCKED_WEB_ELEMENT_FOR_DEFAULT); when(mockedWebDriver.findElements(DEFAULT_LOCATOR)).thenReturn(MOCKED_WEB_ELEMENT_LIST_FOR_DEFAULT); Query.initQueryObjects(mockedWebDriver); }
private void initQueryObjectWithAppiumAndroid() { Capabilities mockedCapabilities = mock(Capabilities.class); when(mockedCapabilities.getbrowserName()).thenReturn(""); when(mockedCapabilities.getPlatform()).thenReturn(Platform.fromString(MobilePlatform.ANDROID)); when(mockedCapabilities.getCapability("automationName")).thenReturn("Appium"); RemoteWebDriver mockedWebDriver = mock(AndroidDriver.class); when(mockedWebDriver.getCapabilities()).thenReturn(mockedCapabilities); when(mockedWebDriver.findElement(DEFAULT_LOCATOR)).thenReturn(MOCKED_MOBILE_ELEMENT_FOR_DEFAULT); when(mockedWebDriver.findElements(DEFAULT_LOCATOR)).thenReturn(MOCKED_MOBILE_ELEMENT_LIST_FOR_DEFAULT); Query.initQueryObjects(mockedWebDriver); }
public DebateFetcher(String chromeDriverFile) throws IOException { service = new ChromeDriverService.Builder() .usingDriverExecutable( new File(chromeDriverFile)) .usingAnyFreePort() .withEnvironment(ImmutableMap.of("disPLAY",":20")).build(); service.start(); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); driver = new RemoteWebDriver(service.getUrl(),capabilities); }
今天关于如何在不清除cookie或缓存的情况下启动Selenium RemoteWebDriver或WebDriver?和开启清除内存不被使用的动态链接文件此项功能的讲解已经结束,谢谢您的阅读,如果想了解更多关于Java Selenium封装--RemoteWebDriver、java – 如何用selenium webdriver发送cookies?、JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测、org.openqa.selenium.remote.RemoteWebDriver的实例源码的相关知识,请在本站搜索。
本文标签: