JSONObject jsonObj = null;
try {
jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
} catch (JSONException e) {
e.printStackTrace();
}
Best Selenium code snippet using org.openqa.selenium.logging.LoggingPreferences
Source: Applogs.java
...75import org.openqa.selenium.chrome.ChromeDriver;76import org.openqa.selenium.logging.LogEntries;77import org.openqa.selenium.logging.LogEntry;78import org.openqa.selenium.logging.LogType;79import org.openqa.selenium.logging.LoggingPreferences;80import org.openqa.selenium.logging.Logs;81import org.openqa.selenium.remote.CapabilityType;82import org.openqa.selenium.remote.DesiredCapabilities;83import org.testng.annotations.AfterMethod;84import org.testng.annotations.BeforeMethod;85import org.testng.annotations.Test;8687public class Applogs {88 private WebDriver driver;89 /* @BeforeMethod90 public void setUp() {91 System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Selenium\\selenium-java-3.141.59\\chromedriver_win32\\chromedriver.exe"); 92 DesiredCapabilities caps = DesiredCapabilities.chrome();93 LoggingPreferences logPrefs = new LoggingPreferences();94 logPrefs.enable(LogType.BROWSER, Level.ALL);95 caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);96 driver = new ChromeDriver(caps);97 }9899 @AfterMethod100 public void tearDown() {101 driver.quit();102 }*/103104 public void analyzeLog(WebDriver driver) {105 /*DesiredCapabilities caps = DesiredCapabilities.chrome();106 LoggingPreferences logPrefs = new LoggingPreferences();107 logPrefs.enable(LogType.BROWSER, Level.ALL);108 caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);109 Logs logs = driver.manage().logs();110 LogEntries logEntries = logs.get(LogType.BROWSER);111 List<LogEntry> errorLogs = logEntries.filter(Level.SEVERE);112 if (errorLogs.size() != 0) {113 fail(errorLogs.size() + " Console error found");114 }115 if(logEntries== null) {116 for (LogEntry entry : logEntries) {117 118 System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());119 do something useful with the data120 }
...
Source: SeleniumDriver.java
...13import org.openqa.selenium.chrome.ChromeOptions;14import org.openqa.selenium.logging.LogEntries;15import org.openqa.selenium.logging.LogEntry;16import org.openqa.selenium.logging.LogType;17import org.openqa.selenium.logging.LoggingPreferences;18import org.openqa.selenium.remote.CapabilityType;19import org.openqa.selenium.remote.DesiredCapabilities;20import java.io.File;21import java.io.FileWriter;22import java.io.IOException;23import java.io.UnsupportedEncodingException;24import java.net.ServerSocket;25import java.net.URLEncoder;26import java.util.Arrays;27import java.util.logging.Level;28/**29 * Created by Erik Krogh Kristensen on 10-11-2015.30 */31public class SeleniumDriver {32 private static String getEmptyPageUrl(String scriptPath, int port) {33 try {34 scriptPath = URLEncoder.encode(scriptPath, "UTF-8");35 } catch (UnsupportedEncodingException e) {36 throw new RuntimeException(e);37 }38 boolean isWindows = System.getProperty("os.name").toLowerCase().contains("windows");39 String workingDir = System.getProperty("user.dir");40 if (isWindows) {41 return "file:///" + workingDir + "\\lib\\selenium\\driver.html?script=" + scriptPath + "&port=" + port;42 } else {43 return "file:///" + workingDir + "/lib/selenium/driver.html?script=" + scriptPath + "&port=" + port;44 }45 }46 public static String executeScript(String script) throws IOException, HttpException {47 setDriverPath();48 ChromeDriver driver = new ChromeDriver(buldCapabilities());49 File scriptFile;50 String tmpFileSuffix = "tmpFileSeleniumDriverThing.js";51 try {52 scriptFile = File.createTempFile("script-", tmpFileSuffix);53 FileWriter out = new FileWriter(scriptFile);54 IOUtils.write(script.getBytes(), out);55 out.close();56 } catch (IOException e) {throw new RuntimeException();}57 ServerSocket socket = new ServerSocket(0);58 int port = socket.getLocalPort();59 System.out.println("Listening for JSNAP at port: " + port);60 driver.get(getEmptyPageUrl(scriptFile.getAbsolutePath(), port));61 String message = getResponse(socket);62 driver.close();63 driver.quit();64 System.out.println("Message recieved, length: " + message.length());65 return message;66 }67 private static String getResponse(ServerSocket serverSocket) throws IOException, HttpException {68 DefaultHttpServerConnection conn = new DefaultHttpServerConnection();69 conn.bind(serverSocket.accept(), new BasicHttpParams());70 HttpRequest request = conn.receiveRequestHeader();71 conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);72 HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();73 return EntityUtils.toString(entity);74 }75 private static LogEntry findJsnapEntry(LogEntries entries) {76 for (LogEntry entry : Lists.reverse(Arrays.asList(Iterators.toArray(entries.iterator(), LogEntry.class)))) {77 if (entry.getLevel() == Level.INFO && entry.getMessage().contains("{\"global\":1")) {78 return entry;79 }80 }81 throw new RuntimeException("Could not find a fitting logEntry");82 }83 private static void setDriverPath() {84 String operatingSystem = System.getProperty("os.name");85 if (operatingSystem.contains("Windows")) {86 System.setProperty("webdriver.chrome.driver", "./lib/selenium/chromedriver.exe");87 } else if (operatingSystem.contains("Linux")) {88 System.setProperty("webdriver.chrome.driver", "./lib/selenium/chromedriverLinux64");89 } else if (operatingSystem.contains("Mac")) {90 System.setProperty("webdriver.chrome.driver", "./lib/selenium/chromedriverMac");91 } else {92 throw new RuntimeException("Unknown operating system: " + operatingSystem);93 }94 }95 private static DesiredCapabilities buldCapabilities() {96 ChromeOptions options = new ChromeOptions();97 options.addArguments("window-size=400,400");98 DesiredCapabilities capabilities = DesiredCapabilities.chrome();99 LoggingPreferences loggingPreferences = new LoggingPreferences();100 loggingPreferences.enable(LogType.BROWSER, Level.ALL);101 capabilities.setCapability(CapabilityType.LOGGING_PREFS, loggingPreferences);102 capabilities.setCapability(ChromeOptions.CAPABILITY, options);103 return capabilities;104 }105}...
Source: testCho.java
...8import org.openqa.selenium.chrome.ChromeOptions;9import org.openqa.selenium.logging.LogEntries;10import org.openqa.selenium.logging.LogEntry;11import org.openqa.selenium.logging.LogType;12import org.openqa.selenium.logging.LoggingPreferences;13import org.openqa.selenium.remote.CapabilityType;14import org.openqa.selenium.remote.DesiredCapabilities;15import java.util.Iterator;16import java.util.logging.Level;17public class testCho {18 @Test19 public void test() {20 System.setProperty("webdriver.chrome.driver","C:\\Users\\Tester\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");21 //设置Webdriverå¯å¨chrome为é»è®¤ç¨æ·çé
置信æ¯ï¼å
æ¬ä¹¦ç¾ãæ©å±ç¨åºçï¼22 ChromeOptions options = new ChromeOptions();23 //为äºè·åconsoleçæ¥å¿è¾åº24 DesiredCapabilities caps = DesiredCapabilities.chrome();25 LoggingPreferences logPrefs = new LoggingPreferences();26 logPrefs.enable(LogType.BROWSER, Level.INFO);//è¾å
¥ä¸ºinfoçæ¥å¿Â 27 caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);28 caps.setCapability(ChromeOptions.CAPABILITY, options);29 //ä¼ å
¥è°·æå¯å¨å¨ä¸30 WebDriver driver = new ChromeDriver(caps);31 driver.manage().window().maximize();//çªå£æå¤§å32 driver.get("http://localhost:7456");//æå¼æµè¯å°å33 LogEntries logEntries =driver.manage().logs().get(LogType.BROWSER);34 while( (driver.manage().logs().get(LogType.BROWSER)!=null)){35 logEntries =driver.manage().logs().get(LogType.BROWSER);36 for(LogEntry entry : logEntries) {37 System.out.println("chrome.console===="+" "+entry.getMessage());38 }39 }40// System.setProperty("webdriver.chrome.driver","C:\\Users\\Tester\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");41// ChromeOptions options = new ChromeOptions();42// LoggingPreferences logPrefs = new LoggingPreferences();43// logPrefs.enable(LogType.PERFORMANCE, Level.INFO);44// DesiredCapabilities cap = DesiredCapabilities.chrome();45// cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);46// options.addArguments("headless");47// //ç¦ç¨æ²çnage48// options.addArguments("no-sandbox");49// options.addArguments("disable-gpu");50// cap.setCapability(ChromeOptions.CAPABILITY, options);51// ChromeDriver driver = new ChromeDriver(cap);52// driver.get("https://www.baidu.com");53// String currentURL = driver.getCurrentUrl();54// LogEntries logs = driver.manage().logs().get("performance");55// int status = -1;56// System.out.println("\nList of log entries:\n");...
Source: WebAutomationService.java
...7import org.openqa.selenium.chrome.ChromeOptions;8import org.openqa.selenium.logging.LogEntries;9import org.openqa.selenium.logging.LogEntry;10import org.openqa.selenium.logging.LogType;11import org.openqa.selenium.logging.LoggingPreferences;12import org.openqa.selenium.remote.DesiredCapabilities;13import org.slf4j.LoggerFactory;14import java.util.concurrent.TimeUnit;15import java.util.logging.Level;16/**17 * Selenium driver automation setup for Enterprise Validator18 *19 * @author Anand Varkey Philips20 * @since 1.0.021 */22@Slf4j23public class WebAutomationService {24 private static final String CHROME_BIN = "CHROME_BIN";25 public WebDriver setUp() {26 if (null == System.getenv(CHROME_BIN)) {27 log.warn("Using Web Driver Manager to download and setup chrome driver");28 Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);29 root.setLevel(ch.qos.logback.classic.Level.INFO);30 WebDriverManager.chromedriver().setup();31 }32 ChromeOptions chromeOptions = new ChromeOptions();33 chromeOptions.addArguments("headless"); //useful for running without opening chrome34 chromeOptions.addArguments("disable-gpu");35 chromeOptions.addArguments("disable-dev-shm-usage");36 chromeOptions.addArguments("no-sandbox");37 // chromeOptions.merge(getCapabilities()); //useful for debugging38 WebDriver driver = new ChromeDriver(chromeOptions);39 driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);40 driver.manage().window().maximize();41 return driver;42 }43 private static DesiredCapabilities getCapabilities() {44 DesiredCapabilities desiredCapabilities = new DesiredCapabilities();45 LoggingPreferences loggingPreferences = new LoggingPreferences();46 loggingPreferences.enable(LogType.BROWSER, Level.ALL);47 loggingPreferences.enable(LogType.DRIVER, Level.ALL);48 loggingPreferences.enable(LogType.PERFORMANCE, Level.INFO);49 desiredCapabilities.setCapability("goog:loggingPrefs", loggingPreferences);50 return desiredCapabilities;51 }52 private static void getLogs(WebDriver driver) {53 LogEntries logEntries = driver.manage().logs().get(LogType.DRIVER);54 for (LogEntry logEntry : logEntries) {55 log.info(logEntry.getTimestamp() + "::" + logEntry.getMessage());56 }57 logEntries = driver.manage().logs().get(LogType.BROWSER);58 for (LogEntry logEntry : logEntries) {59 log.info(logEntry.getTimestamp() + "::" + logEntry.getMessage());...
Source: SeleniumUtil.java
...5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.chrome.ChromeOptions;7import org.openqa.selenium.logging.LogEntry;8import org.openqa.selenium.logging.LogType;9import org.openqa.selenium.logging.LoggingPreferences;10import org.openqa.selenium.logging.Logs;11import org.openqa.selenium.remote.CapabilityType;12public class SeleniumUtil {13 ChromeOptions _options;14 ChromeDriver _driver;15 /**16 * 17 * Download from https://sites.google.com/a/chromium.org/chromedriver18 * 19 * @param chromedriverPath eg20 * "/home/vic/Downloads/chromedriver_linux64/chromedriver"21 */22 public SeleniumUtil(String chromedriverPath) {23 System.setProperty("webdriver.chrome.driver", chromedriverPath);24 }25 public ChromeOptions getOptions() {26 _options = new ChromeOptions();27 _options.addArguments("--disable-extensions");28 _options.addArguments("--no-sandbox");29 _options.addArguments("disable-infobars");30 _options.addArguments("window-size=1920x1200");31 LoggingPreferences logPrefs = new LoggingPreferences();32 logPrefs.enable(LogType.BROWSER, Level.ALL);33 logPrefs.enable(LogType.PERFORMANCE, Level.INFO);34 logPrefs.enable(LogType.PROFILER, Level.INFO);35 _options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);36 _options.getCapability(CapabilityType.LOGGING_PREFS);37 // options.setHeadless(true);38 return _options;39 }40 public ChromeDriver getDriver(ChromeOptions options) {41 _driver = new ChromeDriver(options);42 return _driver;43 }44 public Object exec(ChromeDriver driver, StringBuilder arg) {45 /*...
Source: StepDefinition.java
...7import org.openqa.selenium.chrome.ChromeDriver;8import org.openqa.selenium.logging.LogEntries;9import org.openqa.selenium.logging.LogEntry;10import org.openqa.selenium.logging.LogType;11import org.openqa.selenium.logging.LoggingPreferences;12import org.openqa.selenium.remote.CapabilityType;13import org.openqa.selenium.remote.DesiredCapabilities;14import cucumber.api.java.en.Then;15import cucumber.api.java.en.When;16public class StepDefinition {17 public WebDriver driver;18 @When("^user launch the \"([^\"]*)\" browser$")19 public void user_launch_the_browser(String browser) throws Exception {20 if (browser.toLowerCase().contains("chrome")) {21 System.setProperty("webdriver.chrome.driver", "Driver/chromedriver");22 driver = new ChromeDriver(); 23 }24 DesiredCapabilities caps = DesiredCapabilities.chrome();25 LoggingPreferences logPrefs = new LoggingPreferences();26 logPrefs.enable(LogType.BROWSER, Level.ALL);27 caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);28 }29 @Then("^I verify console errors in \"([^\"]*)\" page$")30 public void i_verify_console_errors_in_page(String url) throws Exception {31 driver.get(url);32 LogEntries logs = driver.manage().logs().get(LogType.BROWSER);33 for (LogEntry entry : logs) {34 System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());35 }36 driver.quit();37 }38 @Then("^I verify page response from \"([^\"]*)\" page$")39 public void verify_response_page(String url) throws Exception {...
Source: JavaScriptErrorTest.java
...7//import org.openqa.selenium.chrome.ChromeDriver;8//import org.openqa.selenium.logging.LogEntries;9//import org.openqa.selenium.logging.LogEntry;10//import org.openqa.selenium.logging.LogType;11//import org.openqa.selenium.logging.LoggingPreferences;12//import org.openqa.selenium.remote.CapabilityType;13//import org.openqa.selenium.remote.DesiredCapabilities;14//import java.util.Date;15//import java.util.logging.Level;16//17//public class JavaScriptErrorTest {18//19// public WebDriver driver;20//21// @Before22// public void setup(){23//24// DesiredCapabilities capabilities = DesiredCapabilities.chrome();25// LoggingPreferences loggingPreferences = new LoggingPreferences();26// loggingPreferences.enable(LogType.BROWSER, Level.ALL);27// capabilities.setCapability(CapabilityType.LOGGING_PREFS, loggingPreferences);28// System.setProperty("webdriver.chrome.driver","C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");29// driver = new ChromeDriver(capabilities);30//31//32// }33//34// @After35// public void teardown(){36// driver.quit();37//38// }39//...
Source: AnimeDownloaderTest.java
...3import org.openqa.selenium.chrome.ChromeOptions;4import org.openqa.selenium.logging.LogEntries;5import org.openqa.selenium.logging.LogEntry;6import org.openqa.selenium.logging.LogType;7import org.openqa.selenium.logging.LoggingPreferences;8import org.openqa.selenium.remote.CapabilityType;9import org.openqa.selenium.remote.DesiredCapabilities;10import java.util.logging.Level;11public class AnimeDownloaderTest {12 static QuitAwareChromeDriver d;13 public static void main(String[] args) {14 System.setProperty(15 "webdriver.chrome.driver",16 "/home/stefano/Develop/Java/AnimeDownloader/drivers/chromedriver"17 );18 ChromeOptions co = new ChromeOptions();19 DesiredCapabilities caps = DesiredCapabilities.chrome();20 LoggingPreferences logPrefs = new LoggingPreferences();21 logPrefs.enable(LogType.PERFORMANCE, Level.ALL);22 caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);23 co.merge(caps);24 d = new QuitAwareChromeDriver(co);25 doGet();26 }27 public static void doGet() {28 d.get("https://www.google.com/");29 LogEntries logEntries = d.manage().logs().get(LogType.PERFORMANCE);30 System.out.println("Printing log entries");31 for (LogEntry logEntry : logEntries) {32 System.out.println(logEntry.getMessage());33 }34 }...
LoggingPreferences
Using AI Code Generation
1LoggingPreferences logPrefs = new LoggingPreferences();2logPrefs.enable(LogType.BROWSER, Level.ALL);3logPrefs.enable(LogType.CLIENT, Level.ALL);4logPrefs.enable(LogType.DRIVER, Level.ALL);5logPrefs.enable(LogType.PERFORMANCE, Level.ALL);6logPrefs.enable(LogType.PROFILER, Level.ALL);7logPrefs.enable(LogType.SERVER, Level.ALL);8DesiredCapabilities caps = DesiredCapabilities.chrome();9caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);10DesiredCapabilities caps = DesiredCapabilities.chrome();11caps.setCapability(CapabilityType.LOGGING_PREFS, ImmutableMap.of(12 LogType.SERVER, Level.ALL));
LoggingPreferences
Using AI Code Generation
1import org.openqa.selenium.chrome.ChromeOptions;2import org.openqa.selenium.logging.LogType;3import org.openqa.selenium.logging.LoggingPreferences;4import java.util.logging.Level;5LoggingPreferences logPrefs = new LoggingPreferences();6logPrefs.enable(LogType.BROWSER, Level.ALL);7logPrefs.enable(LogType.CLIENT, Level.ALL);8logPrefs.enable(LogType.DRIVER, Level.ALL);9logPrefs.enable(LogType.PERFORMANCE, Level.ALL);10logPrefs.enable(LogType.PROFILER, Level.ALL);11logPrefs.enable(LogType.SERVER, Level.ALL);12ChromeOptions options = new ChromeOptions();13options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);14capabilities.setCapability(ChromeOptions.CAPABILITY, options);15import org.openqa.selenium.firefox.FirefoxOptions;16import org.openqa.selenium.logging.LogType;17import org.openqa.selenium.logging.LoggingPreferences;18import java.util.logging.Level;19LoggingPreferences logPrefs = new LoggingPreferences();20logPrefs.enable(LogType.BROWSER, Level.ALL);21logPrefs.enable(LogType.CLIENT, Level.ALL);22logPrefs.enable(LogType.DRIVER, Level.ALL);23logPrefs.enable(LogType.PERFORMANCE, Level.ALL);24logPrefs.enable(LogType.PROFILER, Level.ALL);25logPrefs.enable(LogType.SERVER, Level.ALL);26FirefoxOptions options = new FirefoxOptions();27options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);28capabilities.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options);29import org.openqa.selenium.ie.InternetExplorerOptions;30import org.openqa.selenium.logging.LogType;31import org.openqa.selenium.logging.LoggingPreferences;32import java.util.logging.Level;33LoggingPreferences logPrefs = new LoggingPreferences();34logPrefs.enable(LogType.BROWSER, Level.ALL);35logPrefs.enable(LogType
LoggingPreferences
Using AI Code Generation
1package org.seleniumhq.selenium;2import org.openqa.selenium.logging.LogType;3import org.openqa.selenium.logging.LoggingPreferences;4import org.openqa.selenium.remote.CapabilityType;5import org.openqa.selenium.remote.DesiredCapabilities;6import java.util.logging.Level;7public class DesiredCapabilitiesExample {8 public static void main(String[] args) {9 LoggingPreferences logPrefs = new LoggingPreferences();10 logPrefs.enable(LogType.BROWSER, Level.ALL);11 DesiredCapabilities caps = DesiredCapabilities.chrome();12 caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);13 System.out.println(caps.getCapability(CapabilityType.LOGGING_PREFS));14 }15}
LoggingPreferences
Using AI Code Generation
1import org.openqa.selenium.chrome.ChromeOptions;2import org.openqa.selenium.chrome.ChromeDriver;3import org.openqa.selenium.remote.DesiredCapabilities;4import java.util.logging.Level;5import org.openqa.selenium.logging.LogType;6import org.openqa.selenium.logging.LoggingPreferences;7import java.util.logging.Logger;8public class ChromeBrowserLogs {9 public static void main(String[] args) {10 LoggingPreferences logPrefs = new LoggingPreferences();11 logPrefs.enable(LogType.BROWSER, Level.ALL);12 DesiredCapabilities capabilities = DesiredCapabilities.chrome();13 capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);14 ChromeOptions options = new ChromeOptions();15 options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);16 ChromeDriver driver = new ChromeDriver(options);17 LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);18 for (LogEntry entry : logEntries) {19 System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());20 }21 driver.quit();22 }23}
LoggingPreferences
Using AI Code Generation
1import org.openqa.selenium.logging.LogType;2import org.openqa.selenium.logging.LoggingPreferences;3import org.openqa.selenium.remote.CapabilityType;4import org.openqa.selenium.remote.DesiredCapabilities;5import java.util.logging.Level;6LoggingPreferences logPrefs = new LoggingPreferences();7logPrefs.enable(LogType.BROWSER, Level.ALL);8logPrefs.enable(LogType.PERFORMANCE, Level.ALL);9DesiredCapabilities capabilities = new DesiredCapabilities();10capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);11driver.manage().logs().get(LogType.BROWSER).forEach(l -> System.out.println(l));12driver.manage().logs().get(LogType.PERFORMANCE).forEach(l -> System.out.println(l));13", true));14", true));15", true));16", true));17", true));
LoggingPreferences
Using AI Code Generation
1LoggingPreferences logs = new LoggingPreferences();2logs.enable(LogType.BROWSER, Level.ALL);3DesiredCapabilities dc = DesiredCapabilities.firefox();4dc.setCapability(CapabilityType.LOGGING_PREFS, logs);5WebDriver driver = new FirefoxDriver(dc);6LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);7for (LogEntry entry : logEntries) {8 System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());9}10driver.quit();
1JSONObject jsonObj = null;2 try {3 jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");4 } catch (JSONException e) {5 e.printStackTrace();6 }7
1public static String beanToJSONString(Object myJavaBean) throws Exception {2 ObjectMapper jacksonObjMapper = new ObjectMapper();3 return jacksonObjMapper.writeValueAsString(myJavaBean);4}5
1private static JSONObject createJSONObject(String jsonString){2 JSONObject jsonObject=new JSONObject();3 JSONParser jsonParser=new JSONParser();4 if ((jsonString != null) && !(jsonString.isEmpty())) {5 try {6 jsonObject=(JSONObject) jsonParser.parse(jsonString);7 } catch (org.json.simple.parser.ParseException e) {8 e.printStackTrace();9 }10 }11 return jsonObject;12}13
How to resolve, Stale element exception? if element is no longer attached to the DOM?
Selenium WebDriver: How to wait for iFrames to load completely?
org.openqa.selenium.remote.internal.ApacheHttpClient is deprecated in Selenium 3.14.0 - What should be used instead?
How to execute a Selenium test in Java
How to interact with the elements within #shadow-root (open) while Clearing Browsing Data of Chrome Browser using cssSelector
Using a Java library with Scala reserved words
Selenium webdriver: Modifying navigator.webdriver flag to prevent selenium detection
How to stop TestNG from running after a test fail
Xpath for button having text as 'New'
How to click an image with Selenium with only an SRC
The problem you are probably facing is that the method returns the right (and valid!) element, but when you're trying to access it a second later, it is stale and throws.
This usually arises when:
There are four ways to solve it I know about:
Use proper waits after every anticipated page-load when facing asynchronous pages. Insert an explicit wait after the initial click and wait for the new page / new content to load. Only after that you can try to search for the element you want. This should be the first thing you'll do. It will increase the robustness of your tests greatly.
I have been using a variant of your method for two years now (together with the technique above in solution 1) and it absolutely works most of the time and fails only on strange WebDriver bugs. Try to access the found element right after it is found (before returning from the method) via a .isDisplayed()
method or something. If it throws, you already know how to search again. If it passes, you have one more (false) assurance.
Write a WebElement
decorator that remembers how it was found and re-find it when it's accessed and throws. This obviously forces you to use custom findElement()
methods that would return instances of your decorator (or, better yet, a decorated WebDriver
that would return your instances from usual findElement()
and findElemens()
methods). Do it like this:
public class NeverStaleWebElement implements WebElement {
private WebElement element;
private final WebDriver driver;
private final By foundBy;
public NeverStaleWebElement(WebElement element, WebDriver driver, By foundBy) {
this.element = element;
this.driver = driver;
this.foundBy = foundBy;
}
@Override
public void click() {
try {
element.click();
} catch (StaleElementReferenceException e) {
// log exception
// assumes implicit wait, use custom findElement() methods for custom behaviour
element = driver.findElement(foundBy);
// recursion, consider a conditioned loop instead
click();
}
}
// ... similar for other methods, too
}
Note that while I think that the foundBy
info should be accessible from the generic WebElements to make this easier, Selenium developers consider it a mistake to try something like this and have chosen not to make this information public. It's arguably a bad practice to re-find on stale elements, because you're re-finding elements implicitly without any mechanism for checking whether it's justified. The re-finding mechanism could potentially find a completely different element and not the same one again. Also, it fails horribly with findElements()
when there are many found elements (you either need to disallow re-finding on elements found by findElements()
, or remember the how-manyeth your element was from the returned List
).
I think it would be useful sometimes, but it's true that nobody would ever use options 1 and 2 which are obviously much better solutions for the robustness of your tests. Use them and only after you're sure you need this, go for it.
Implement your whole workflow in a new way!
@LoadsNewPage
, @Reversible
etc. as needed.This would obviously take a lot of effort and if not thought through very well, could backfire soon. I used a (lot more complex and powerful) variant of this for resuming failed tests after I manually fixed the page they were on. Under some conditions (for example, on a StaleElementException
), a fail would not end the test right away, but would wait (before finally time-outing after 15 seconds), popping up an informative window and giving the user an option to manually refresh the page / click the right button / fix the form / whatever. It would then re-run the failed task or even give a possibility to go some steps back in history (e.g. to the last @LoadsNewPage
job).
All that said, your original solution could use some polishing. You could combine the two methods into one, more general (or at least make them delegate to this one to reduce code repetition):
WebElement getStaleElem(By by, WebDriver driver) {
try {
return driver.findElement(by);
} catch (StaleElementReferenceException e) {
System.out.println("Attempting to recover from StaleElementReferenceException ...");
return getStaleElem(by, driver);
} catch (NoSuchElementException ele) {
System.out.println("Attempting to recover from NoSuchElementException ...");
return getStaleElem(by, driver);
}
}
With Java 7, even a single multicatch block would be sufficient:
WebElement getStaleElem(By by, WebDriver driver) {
try {
return driver.findElement(by);
} catch (StaleElementReferenceException | NoSuchElementException e) {
System.out.println("Attempting to recover from " + e.getClass().getSimpleName() + "...");
return getStaleElem(by, driver);
}
}
This way, you can greatly reduce the amount of code you need to maintain.
Check out the latest blogs from LambdaTest on this topic:
I still remember the day when our delivery manager announced that from the next phase, the project is going to be Agile. After attending some training and doing some online research, I realized that as a traditional tester, moving from Waterfall to agile testing team is one of the best learning experience to boost my career. Testing in Agile, there were certain challenges, my roles and responsibilities increased a lot, workplace demanded for a pace which was never seen before. Apart from helping me to learn automation tools as well as improving my domain and business knowledge, it helped me get close to the team and participate actively in product creation. Here I will be sharing everything I learned as a traditional tester moving from Waterfall to Agile.
What happens when you are chit chatting and ran out of words? Or facing the urge to keep up with the twitter word limit maintaining your emotions? In every way, digital media is relying on Emojis. The ultimate hero that always came at your aid when you run out of words. The enormous use of emoticons in the past years has explained how important they are to us in today’s world.
One of the major hurdles that web-developers, as well as app developers, the face is ‘Testing their website/app’ across different browsers. The testing mechanism is also called as ‘Cross Browser Testing’. There are so many browsers and browser versions (Google Chrome, Mozilla Firefox, Internet Explorer, Microsoft Edge, Opera, Yandex, etc.), numerous ways in which your website/app can be accessed (via desktop, smartphones, tablets, etc.) and numerous operating systems (Windows, MacOS, Linux, Android, iOS, etc.) which might be used to access your website.
The necessity for vertical text-orientation might not seem evident at first and its use rather limited solely as a design aspect for web pages. However, many Asian languages like Mandarin or Japanese scripts can be written vertically, flowing from right to left or in case of Mongolian left to right. In such languages, even though the block-flow direction is sideways either left to right or right to left, letters or characters in a line flow vertically from top to bottom. Another common use of vertical text-orientation can be in table headers. This is where text-orientation property becomes indispensable.
Testing has always been a bane of the product development cycle. In an era where a single software bug can cause massive financial losses, quality assurance testing is paramount for any software product no matter how small or how big.
LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!