Source:How to avoid "StaleElementReferenceException" in Selenium?
From---->To
Best Selenium code snippet using org.openqa.selenium.StaleElementReferenceException
org.openqa.selenium.StaleElementReferenceExceptionThe WebDriver error - stale element reference error, happens when the referenced web element isn't attached to the DOM.
Dom elements in the WebDriver are identified by a unique reference called a web element. The web element reference is a globally unique identifier which is utilised in executing commands to target particular elements like getting the property of an element etc.
In JavaScript, a stale element in the DOM has lost its connection to the document after it was deleted from the document or the document was changed. For example, staleness can occur when the web element reference from the document it is retrieved from is navigated away.
Upon navigating away from the page, all web element references to the previous page will be discarded. A stale element reference error occurs when subsequent interaction with a discarded web element fails because it is no longer in the document:

1import urllib
2
3from selenium import webdriver
4from selenium.common import exceptions
5
6def inline(doc):
7    return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc))
8
9session = webdriver.Firefox()
10session.get(inline("<strong>foo</strong>"))
11foo = session.find_element_by_css_selector("strong")
12
13session.get(inline("<i>bar</i>"))
14try:
15    foo.tag_name
16except exceptions.StaleElementReferenceException as e:
17    print(e)
18
Copy to Clipboard
Output:
1 StaleElementReferenceException: The element reference of e75a1764-ff73-40fa-93c1-08cb90394b65 is stale either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
A document node's web element reference will be invalidated when the node is deleted from the DOM. Any subsequent reference to the web element will also throw the same error:

1import urllib
2
3from selenium import webdriver
4from selenium.common import exceptions
5
6def inline(doc):
7    return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc))
8
9session = webdriver.Firefox()
10session.get(inline("<button>foo</button>"))
11button = session.find_element_by_css_selector("button")
12session.execute_script("""
13    let [button] = arguments;
14    button.remove();
15    """, script_args=(button,))
16
17try:
18    button.click()
19except exceptions.StaleElementReferenceException as e:
20    print(e)
Output:
1 StaleElementReferenceException: The element reference of e75a1764-ff73-40fa-93c1-08cb90394b65 is stale either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
Here are code snippets that can help you understand more how developers are using
Source:RetryWebElementImpl.java  
...17import org.openqa.selenium.By;18import org.openqa.selenium.Dimension;19import org.openqa.selenium.OutputType;20import org.openqa.selenium.Point;21import org.openqa.selenium.StaleElementReferenceException;22import org.openqa.selenium.WebDriver;23import org.openqa.selenium.WebDriverException;24import org.openqa.selenium.WebElement;25import org.openqa.selenium.interactions.internal.Coordinates;26import org.openqa.selenium.internal.Locatable;27import org.openqa.selenium.internal.WrapsDriver;28import org.openqa.selenium.remote.FileDetector;29import org.openqa.selenium.remote.RemoteWebDriver;30import org.openqa.selenium.remote.RemoteWebElement;31/**32 * @author Brian Wing Shun Chan33 * @author Michael Hashimoto34 */35public class RetryWebElementImpl36	extends RemoteWebElement implements Locatable, WebElement, WrapsDriver {37	public RetryWebElementImpl(String locator, WebElement webElement) {38		_locator = locator;39		_webElement = webElement;40		_remoteWebElement = (RemoteWebElement)_webElement;41	}42	@Override43	public void clear() {44		try {45			_webElement.clear();46		}47		catch (StaleElementReferenceException sere) {48			_refreshWebElement(sere);49			_webElement.clear();50		}51	}52	@Override53	public void click() {54		try {55			_webElement.click();56		}57		catch (StaleElementReferenceException sere) {58			_refreshWebElement(sere);59			_webElement.click();60		}61	}62	@Override63	public boolean equals(Object obj) {64		try {65			return _remoteWebElement.equals(obj);66		}67		catch (StaleElementReferenceException sere) {68			_refreshWebElement(sere);69			return _remoteWebElement.equals(obj);70		}71	}72	@Override73	public WebElement findElement(By by) {74		try {75			return _webElement.findElement(by);76		}77		catch (StaleElementReferenceException sere) {78			_refreshWebElement(sere);79			return _webElement.findElement(by);80		}81	}82	@Override83	public WebElement findElementByClassName(String using) {84		try {85			return _remoteWebElement.findElementByClassName(using);86		}87		catch (StaleElementReferenceException sere) {88			_refreshWebElement(sere);89			return _remoteWebElement.findElementByClassName(using);90		}91	}92	@Override93	public WebElement findElementByCssSelector(String using) {94		try {95			return _remoteWebElement.findElementByCssSelector(using);96		}97		catch (StaleElementReferenceException sere) {98			_refreshWebElement(sere);99			return _remoteWebElement.findElementByCssSelector(using);100		}101	}102	@Override103	public WebElement findElementByPartialLinkText(String using) {104		try {105			return _remoteWebElement.findElementByPartialLinkText(using);106		}107		catch (StaleElementReferenceException sere) {108			_refreshWebElement(sere);109			return _remoteWebElement.findElementByPartialLinkText(using);110		}111	}112	@Override113	public WebElement findElementByTagName(String using) {114		try {115			return _remoteWebElement.findElementByTagName(using);116		}117		catch (StaleElementReferenceException sere) {118			_refreshWebElement(sere);119			return _remoteWebElement.findElementByTagName(using);120		}121	}122	@Override123	public WebElement findElementByXPath(String using) {124		try {125			return _remoteWebElement.findElementByXPath(using);126		}127		catch (StaleElementReferenceException sere) {128			_refreshWebElement(sere);129			return _remoteWebElement.findElementByXPath(using);130		}131	}132	@Override133	public List<WebElement> findElements(By by) {134		try {135			return _webElement.findElements(by);136		}137		catch (StaleElementReferenceException sere) {138			_refreshWebElement(sere);139			return _webElement.findElements(by);140		}141	}142	@Override143	public List<WebElement> findElementsByClassName(String using) {144		try {145			return _remoteWebElement.findElementsByClassName(using);146		}147		catch (StaleElementReferenceException sere) {148			_refreshWebElement(sere);149			return _remoteWebElement.findElementsByClassName(using);150		}151	}152	@Override153	public List<WebElement> findElementsByCssSelector(String using) {154		try {155			return _remoteWebElement.findElementsByCssSelector(using);156		}157		catch (StaleElementReferenceException sere) {158			_refreshWebElement(sere);159			return _remoteWebElement.findElementsByCssSelector(using);160		}161	}162	@Override163	public List<WebElement> findElementsByPartialLinkText(String using) {164		try {165			return _remoteWebElement.findElementsByPartialLinkText(using);166		}167		catch (StaleElementReferenceException sere) {168			_refreshWebElement(sere);169			return _remoteWebElement.findElementsByPartialLinkText(using);170		}171	}172	@Override173	public List<WebElement> findElementsByTagName(String using) {174		try {175			return _remoteWebElement.findElementsByTagName(using);176		}177		catch (StaleElementReferenceException sere) {178			_refreshWebElement(sere);179			return _remoteWebElement.findElementsByTagName(using);180		}181	}182	@Override183	public List<WebElement> findElementsByXPath(String using) {184		try {185			return _remoteWebElement.findElementsByXPath(using);186		}187		catch (StaleElementReferenceException sere) {188			_refreshWebElement(sere);189			return _remoteWebElement.findElementsByXPath(using);190		}191	}192	@Override193	public String getAttribute(String name) {194		try {195			return _webElement.getAttribute(name);196		}197		catch (StaleElementReferenceException sere) {198			_refreshWebElement(sere);199			return _webElement.getAttribute(name);200		}201	}202	@Override203	public Coordinates getCoordinates() {204		try {205			Locatable locatable = (Locatable)_webElement;206			return locatable.getCoordinates();207		}208		catch (StaleElementReferenceException sere) {209			_refreshWebElement(sere);210			Locatable locatable = (Locatable)_webElement;211			return locatable.getCoordinates();212		}213	}214	@Override215	public String getCssValue(String propertyName) {216		try {217			return _webElement.getCssValue(propertyName);218		}219		catch (StaleElementReferenceException sere) {220			_refreshWebElement(sere);221			return _webElement.getCssValue(propertyName);222		}223	}224	@Override225	public String getId() {226		try {227			return _remoteWebElement.getId();228		}229		catch (StaleElementReferenceException sere) {230			_refreshWebElement(sere);231			return _remoteWebElement.getId();232		}233	}234	@Override235	public Point getLocation() {236		try {237			return _webElement.getLocation();238		}239		catch (StaleElementReferenceException sere) {240			_refreshWebElement(sere);241			return _webElement.getLocation();242		}243	}244	@Override245	public <X> X getScreenshotAs(OutputType<X> target)246		throws WebDriverException {247		try {248			return _webElement.getScreenshotAs(target);249		}250		catch (StaleElementReferenceException sere) {251			_refreshWebElement(sere);252			return _webElement.getScreenshotAs(target);253		}254	}255	@Override256	public Dimension getSize() {257		try {258			return _webElement.getSize();259		}260		catch (StaleElementReferenceException sere) {261			_refreshWebElement(sere);262			return _webElement.getSize();263		}264	}265	@Override266	public String getTagName() {267		try {268			return _webElement.getTagName();269		}270		catch (StaleElementReferenceException sere) {271			_refreshWebElement(sere);272			return _webElement.getTagName();273		}274	}275	@Override276	public String getText() {277		try {278			return _webElement.getText();279		}280		catch (StaleElementReferenceException sere) {281			_refreshWebElement(sere);282			return _webElement.getText();283		}284	}285	@Override286	public WebDriver getWrappedDriver() {287		return WebDriverUtil.getWebDriver();288	}289	@Override290	public int hashCode() {291		try {292			return _remoteWebElement.hashCode();293		}294		catch (StaleElementReferenceException sere) {295			_refreshWebElement(sere);296			return _remoteWebElement.hashCode();297		}298	}299	@Override300	public boolean isDisplayed() {301		try {302			return _webElement.isDisplayed();303		}304		catch (StaleElementReferenceException sere) {305			_refreshWebElement(sere);306			return _webElement.isDisplayed();307		}308	}309	@Override310	public boolean isEnabled() {311		try {312			return _webElement.isEnabled();313		}314		catch (StaleElementReferenceException sere) {315			_refreshWebElement(sere);316			return _webElement.isEnabled();317		}318	}319	@Override320	public boolean isSelected() {321		try {322			return _webElement.isSelected();323		}324		catch (StaleElementReferenceException sere) {325			_refreshWebElement(sere);326			return _webElement.isSelected();327		}328	}329	public void sendKeys(CharSequence... keys) {330		try {331			_webElement.sendKeys(keys);332		}333		catch (StaleElementReferenceException sere) {334			_refreshWebElement(sere);335			_webElement.sendKeys(keys);336		}337	}338	@Override339	public void setFileDetector(FileDetector fileDetector) {340		try {341			_remoteWebElement.setFileDetector(fileDetector);342		}343		catch (StaleElementReferenceException sere) {344			_refreshWebElement(sere);345			_remoteWebElement.setFileDetector(fileDetector);346		}347	}348	@Override349	public void setId(String id) {350		try {351			_remoteWebElement.setId(id);352		}353		catch (StaleElementReferenceException sere) {354			_refreshWebElement(sere);355			_remoteWebElement.setId(id);356		}357	}358	@Override359	public void setParent(RemoteWebDriver remoteWebDriver) {360		try {361			_remoteWebElement.setParent(remoteWebDriver);362		}363		catch (StaleElementReferenceException sere) {364			_refreshWebElement(sere);365			_remoteWebElement.setParent(remoteWebDriver);366		}367	}368	@Override369	public void submit() {370		try {371			_webElement.submit();372		}373		catch (StaleElementReferenceException sere) {374			_refreshWebElement(sere);375			_webElement.submit();376		}377	}378	private void _refreshWebElement(Throwable throwable) {379		System.out.println("\n" + throwable.getMessage());380		System.out.println(381			"\nWill retry command in " + _RETRY_WAIT_TIME + " seconds\n");382		try {383			Thread.sleep(_RETRY_WAIT_TIME * 1000);384		}385		catch (Exception e) {386		}387		WebDriver webDriver = WebDriverUtil.getWebDriver();...Source:Base.java  
...9import org.apache.logging.log4j.Logger;10import org.openqa.selenium.By;11import org.openqa.selenium.JavascriptExecutor;12import org.openqa.selenium.NoSuchElementException;13import org.openqa.selenium.StaleElementReferenceException;14import org.openqa.selenium.WebDriver;15import org.openqa.selenium.WebElement;16import org.openqa.selenium.chrome.ChromeDriver;17import org.openqa.selenium.firefox.FirefoxDriver;18import org.openqa.selenium.interactions.Actions;19import org.openqa.selenium.opera.OperaDriver;20import org.openqa.selenium.support.ui.Select;21import org.openqa.selenium.edge.EdgeDriver;22import io.github.bonigarcia.wdm.WebDriverManager;23public class Base {24	public WebDriver driver;25	public Properties props;26	private static final Logger logger = LogManager.getLogger(Base.class.getName());27	// Making method for driver initialization. This will be used many times.28	public WebDriver initializeDriver() {29		props = new Properties();30		// Loading properties file. There is set what kind of browser i use.31		try {32			String fileName = "data.properties";33			String workingDirectory = System.getProperty("user.dir");34			String absolutePath = workingDirectory + File.separator + "src" + File.separator + "main" + File.separator35					+ "java" + File.separator + "resources" + File.separator + fileName;36			FileInputStream fis = new FileInputStream(absolutePath);37			props.load(fis);38		} catch (FileNotFoundException e) {39			e.printStackTrace();40			System.out.println("Error on calling properties file");41		} catch (IOException e) {42			e.printStackTrace();43			System.out.println("Error on loading properties file");44		}45		// Getting browser information from properties file46		String browserName = props.getProperty("browser");47		// Initializing web driver.48		if (browserName.equals("chrome")) {49			WebDriverManager.chromedriver().setup();50			driver = new ChromeDriver();51		} else if (browserName.equals("firefox")) {52			WebDriverManager.firefoxdriver().setup();53			driver = new FirefoxDriver();54		} else if (browserName.equals("opera")) {55			WebDriverManager.operadriver().setup();56			driver = new OperaDriver();57		} else if (browserName.equals("edge")) {58			WebDriverManager.edgedriver().setup();59			driver = new EdgeDriver();60		}61		return driver;62	}63	public void checkIsElementPresent(WebDriver driver, By locator, int time) {64		boolean isPresent = false;65		int counter = 0;66		driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);67		do {68			try {69				isPresent = driver.findElements(locator).size() > 0;70//				System.out.println(locator.toString() + " rado? - " + isPresent + "; Ieskoma " + counter71//						+ " kartu, laiko intervalas 1s");72				logger.info(locator.toString() + " rado? - " + isPresent + "; Ieskoma " + counter73						+ " kartu, laiko intervalas 1s");74				counter++;75				try {76					Thread.sleep(1000);77				} catch (InterruptedException e) {78					e.printStackTrace();79				}80			} catch (StaleElementReferenceException e) {81				isPresent = false;82//				System.out.println("StaleElementReferenceException - elemento paieska kartojama " + counter);83				logger.error("StaleElementReferenceException - elemento paieska kartojama " + counter);84			} catch (NoSuchElementException e1) {85				isPresent = false;86//				System.out.println("NoSuchElementException - elemento paieska kartojama " + counter);87				logger.error("NoSuchElementException - elemento paieska kartojama " + counter);88				89			}90		} while (!isPresent && counter != time);91		driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);92	}93	public boolean isFileDownloaded(String downloadPath, String fileName) {94		File dir = new File(downloadPath);95		File[] dirContents = dir.listFiles();96		for (int i = 0; i < dirContents.length; i++) {97			if (dirContents[i].getName().equals(fileName)) {98				// File has been found, it can now be deleted:99				dirContents[i].delete();100				return true;101			}102		}103		return false;104	}105	public void click(WebDriver driver, By locator, int time) {106		checkIsElementPresent(driver, locator, time);107		WebElement element = driver.findElement(locator);108		int attempts = 0;109		do {110			try {111				Actions actions = new Actions(driver);112				actions.moveToElement(element);113				actions.click();114				actions.perform();115				break;116			} catch (StaleElementReferenceException e) {117				// wait one sec118				try {119					Thread.sleep(1000);120				} catch (InterruptedException e1) {121					e1.printStackTrace();122				}123//				System.out.println("StaleElementReferenceException - elemento paieska kartojama " + attempts);124				logger.error("StaleElementReferenceException - elemento paieska kartojama " + attempts);125			} catch (NoSuchElementException e) {126				try {127					Thread.sleep(500);128				} catch (InterruptedException e2) {129					e2.printStackTrace();130				}131//				System.out.println("NoSuchElementException - elemento paieska kartojama " + attempts);132				logger.error("NoSuchElementException - elemento paieska kartojama " + attempts);133			}134			attempts++;135		} while (attempts < time);136	}137	public void type(WebDriver driver, By locator, String value, int time) {138		WebElement element = driver.findElement(locator);139		checkIsElementPresent(driver, locator, time);140		Actions actions = new Actions(driver);141		int attempts = 0;142		while (attempts < time) {143			try {144				actions.moveToElement(element);145				actions.click();146				actions.perform();147				try {148					Thread.sleep(1000);149				} catch (InterruptedException e) {150					e.printStackTrace();151				}152				actions.sendKeys(value);153				actions.perform();154				break;155			} catch (StaleElementReferenceException e) {156				try {157					Thread.sleep(1000);158				} catch (InterruptedException e1) {159					e1.printStackTrace();160				}161//				System.out.println("StaleElementReferenceException - elemento paieska kartojama " + attempts);162				logger.error("StaleElementReferenceException - elemento paieska kartojama " + attempts);163			} catch (NoSuchElementException e) {164				try {165					Thread.sleep(1000);166				} catch (InterruptedException e1) {167					e1.printStackTrace();168				}169//				System.out.println("NoSuchElementException - elemento paieska kartojama " + attempts);170				logger.error("NoSuchElementException - elemento paieska kartojama " + attempts);171				172			}173			attempts++;174		}175	}176	public void select(WebDriver driver, By locator, String value, int time) {177		WebElement element = driver.findElement(locator);178		checkIsElementPresent(driver, locator, time);179		int attempts = 0;180		do {181			try {182				Select s = new Select(element);183				s.selectByVisibleText(value);184				break;185			} catch (StaleElementReferenceException e) {186				// wait one sec187				try {188					Thread.sleep(1000);189				} catch (InterruptedException e1) {190					e1.printStackTrace();191				}192//				System.out.println("StaleElementReferenceException - elemento paieska kartojama " + attempts);193				logger.error("StaleElementReferenceException - elemento paieska kartojama " + attempts);194			} catch (NoSuchElementException e) {195				try {196					Thread.sleep(500);197				} catch (InterruptedException e2) {198					e2.printStackTrace();199				}200//				System.out.println("NoSuchElementException - elemento paieska kartojama " + attempts);201				logger.error("NoSuchElementException - elemento paieska kartojama " + attempts);202				203			}204			attempts++;205		} while (attempts < time);206	}207	public String getTextOfinput(WebDriver driver, By locator) {...Source:R12DirectDepositPage.java  
23import org.openqa.selenium.JavascriptExecutor;4import org.openqa.selenium.Keys;5import org.openqa.selenium.NoSuchElementException;6import org.openqa.selenium.StaleElementReferenceException;7import org.openqa.selenium.WebDriver;8import org.openqa.selenium.WebElement;9import org.openqa.selenium.support.FindBy;10import org.openqa.selenium.support.PageFactory;11import org.openqa.selenium.support.ui.ExpectedConditions;12import org.openqa.selenium.support.ui.Select;13import org.openqa.selenium.support.ui.WebDriverWait;1415public class R12DirectDepositPage 16{	17	WebDriver driver;18	19	@FindBy(xpath="//*[contains(@id,'F3::content')]")20	WebElement EmployeeBox;21	22	@FindBy(xpath="//*[contains(@id,'F4::content')]")23	WebElement EmployeeDescBox;24	25	@FindBy(xpath="//*[contains(@id,'S1CONT2T:PYEMPSALSPL_INSERTRECORD_toolbarButton')]")26	WebElement InsertButton;27	28	@FindBy(xpath="//*[contains(@id,'t:0:F10_t::content')]")29	WebElement PriorityBox;30	31	@FindBy(xpath="//*[contains(@id,'t:0:F14_t::content')]")32	WebElement PercentBox;33	34	@FindBy(xpath="//*[contains(@id,'S1CONT2T:t:F14_ct')]")35	WebElement TotalPercentDescBox;36	37	@FindBy(xpath="//*[contains(@id,'t:0:F15_t::content')]")38	WebElement SplitTypeMenu;39	40	@FindBy(xpath="//*[contains(@id,'t:0:F16_t::content')]")41	WebElement BankBox;42	43	@FindBy(xpath="//*[contains(@id,'t:0:F18_t::content')]")44	WebElement BankDescBox;45	46	@FindBy(xpath="//*[contains(@id,'t:0:F17_t::content')]")47	WebElement BranchBox;48	49	@FindBy(xpath="//*[contains(@id,'t:0:F21_t::content')]")50	WebElement CodeBox;51	52	@FindBy(xpath="//*[contains(@id,'t:0:F20_t::content')]")53	WebElement CountBox;54	55	@FindBy(xpath="//*[contains(@id,'t:0:F22_t::content')]")56	WebElement AccountNumberBox;57	58	@FindBy(xpath="//*[contains(@id,'Main_save')]")59	WebElement SaveButton;60	61	@FindBy(xpath="//*[contains(text(),'Total Percentage must be 100')]")62	WebElement TotalPercentErrorMessageBox;63	64	@FindBy(xpath="//*[contains(@id,'t:1:F10_t::content')]")65	WebElement PriorityBox2;66	67	@FindBy(xpath="//*[contains(@id,'t:1:F14_t::content')]")68	WebElement PercentBox2;69	70	@FindBy(xpath="//*[contains(@id,'S1CONT2T:PYEMPSALSPL_DELETERECORD_toolbarButton')]")71	WebElement DeleteButton;72	73	@FindBy(xpath="//*[contains(@id,'S1CONT2T:t::hscroller')]")74	WebElement accountDetailsScrollBar;75	76	public R12DirectDepositPage(WebDriver driver)77	{78		this.driver=driver;79		PageFactory.initElements(driver, this);80	}81	82	public void enterEmployee(String employee)83	{	84		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(EmployeeBox));85		EmployeeBox.sendKeys(employee);86		EmployeeBox.sendKeys(Keys.TAB);87		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.attributeToBeNotEmpty(EmployeeDescBox,"value"));88	}89	90	public void clickInsertButton1()91	{92		InsertButton.click();93		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(PriorityBox));94	}95	96	public void enterPriority(String priority)97	{	98		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(PriorityBox));99		PriorityBox.sendKeys(priority);100		PriorityBox.sendKeys(Keys.TAB);101	}102	103	public void enterPercentFigure1(String percent)104	{105		PercentBox.sendKeys(percent);106		PercentBox.sendKeys(Keys.TAB);107		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.textToBePresentInElement(TotalPercentDescBox, percent));108		109	}110	111	public void selectDirectDepositSplitType()112	{113		new Select(SplitTypeMenu).selectByValue("1");114		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(BankBox));115	}116	117	public void enterBank(String bank)118	{119		BankBox.sendKeys(bank);120		BankBox.sendKeys(Keys.TAB);121		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.attributeToBeNotEmpty(BankDescBox,"value"));122	}123	124	public void enterBranch(String branch)125	{126		BranchBox.sendKeys(branch);127		BranchBox.sendKeys(Keys.TAB);128	}129	130	public void enterCode(String code)131	{132		CodeBox.sendKeys(code);133		CodeBox.sendKeys(Keys.TAB);134		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.attributeToBeNotEmpty(CountBox,"value"));135	}136	137	public void enterAccountNumber(String accountNum)138	{139		AccountNumberBox.sendKeys(accountNum);140		AccountNumberBox.sendKeys(Keys.TAB);141	}142	143	public void clickSave1()144	{145		SaveButton.click();146		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.visibilityOf(TotalPercentErrorMessageBox));147	}148	149	public void clickInsertButton2()150	{	151		((JavascriptExecutor) driver).executeScript("arguments[0].scrollLeft += -500", accountDetailsScrollBar);152		InsertButton.click();153		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(PriorityBox2));154	}155	156	public void enterPriority2(String priority2)157	{	158		159		PriorityBox2.sendKeys(priority2);160		PriorityBox2.sendKeys(Keys.TAB);161	}162	163	public void enterPercentFigure2(String percent2)164	{165		PercentBox2.sendKeys(percent2);166		PercentBox2.sendKeys(Keys.TAB);167		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.textToBePresentInElement(TotalPercentDescBox, "100"));168	}169	170	public void clickSave2()171	{172		SaveButton.click();173		try {174			Thread.sleep(5000);175		} catch (InterruptedException e) {176			// TODO Auto-generated catch block177			e.printStackTrace();178		}179		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.textToBePresentInElement(TotalPercentDescBox, "100"));180	}181	182	public String returnSavedTotalPercentage()183	{184		return TotalPercentDescBox.getText();185	}186	187	public void clickDeleteToDeleteAllRows()188	{	189		try190		{191				new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(DeleteButton));192				DeleteButton.click();193				new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.textToBePresentInElement(TotalPercentDescBox, "65"));194				195			196		}197		catch(NoSuchElementException e)198		{199			200		}201		202		try203		{204			new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(DeleteButton));205			DeleteButton.click();206			new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.textToBePresentInElement(TotalPercentDescBox, "0"));207			208		}209		catch(NoSuchElementException e)210		{211			212		}213		214	}215	216	public void clickSaveAfterDeletion()217	{218		SaveButton.click();219		try {220			Thread.sleep(4000);221		} catch (InterruptedException e) {222			// TODO Auto-generated catch block223			e.printStackTrace();224		}225		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.textToBePresentInElement(TotalPercentDescBox, "0"));226		227	}228}
...Source:Utility.java  
...7import java.util.function.Function;89import org.openqa.selenium.By;10import org.openqa.selenium.JavascriptExecutor;11import org.openqa.selenium.StaleElementReferenceException;12import org.openqa.selenium.WebDriver;13import org.openqa.selenium.WebElement;14import org.openqa.selenium.chrome.ChromeDriver;15import org.openqa.selenium.edge.EdgeDriver;16import org.openqa.selenium.firefox.FirefoxDriver;17import org.openqa.selenium.opera.OperaDriver;18import org.openqa.selenium.support.ui.ExpectedCondition;19import org.openqa.selenium.support.ui.FluentWait;20import org.openqa.selenium.support.ui.Wait;21import org.openqa.selenium.support.ui.WebDriverWait;22import org.testng.Reporter;2324import io.github.bonigarcia.wdm.WebDriverManager;2526public class Utility {27	private static String className;28	29	public static void selection_dropdown(WebDriver driver, String xpathvalue, String expectedData) {30		List<WebElement> GroupOfelements=driver.findElements(By.xpath(xpathvalue));3132		for(WebElement eachElement:GroupOfelements) {33			String actualData=eachElement.getText();34			35			if (actualData.equalsIgnoreCase(expectedData)) {36				((JavascriptExecutor)driver).executeScript("arguments[0].click();", eachElement);37				System.out.println(actualData + " Is selected from the dropdown");38				break;39			}40		}41	}42	43	public static WebElement staleElement(WebDriver driver, String xpath) throws Exception{44		WebElement element=null;;45		for(int i=1;i<=2;i++) {46			try {47				element=driver.findElement(By.xpath(xpath));48				break;			49			}catch(StaleElementReferenceException se) {50				Thread.sleep(1000);51				Reporter.log("StaleElementReferenceException occured, retrying for same element...!!!", true);52			}catch(Exception e) {53				Reporter.log("Exception occurred while finding the element...!!!", true);54				e.getStackTrace();55			}56			57		}58		return element;59	}60	61	public static boolean retryClick(WebDriver driver, By by) throws Exception{		62		boolean result = false;63		64		for(int attempts = 0;attempts<2;attempts++) {65			try {66					//driver.findElement(by).click();67					((JavascriptExecutor)driver).executeScript("arguments[0].click();", driver.findElement(by));68		            result = true;69		            break;70			} catch(StaleElementReferenceException e) {71				Reporter.log("StaleElementReferenceException occured, retrying for same element...!!!", true);72			}73			74		}75		return result;		76	}77	78	public static WebDriver getDriver(String browser) {79		WebDriver driver=null;80		if(browser.equalsIgnoreCase("Chrome")) {81			WebDriverManager.chromedriver().setup();82			driver = new ChromeDriver();83		}else if(browser.equalsIgnoreCase("Firefox")) {84			WebDriverManager.firefoxdriver().setup();85			driver = new FirefoxDriver();
...Source:CommonBase.java  
1package PAGE;2import org.openqa.selenium.ElementNotVisibleException;3import org.openqa.selenium.JavascriptExecutor;4import org.openqa.selenium.NoSuchElementException;5import org.openqa.selenium.StaleElementReferenceException;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebElement;8import org.openqa.selenium.chrome.ChromeDriver;9import org.openqa.selenium.firefox.FirefoxDriver;10import org.openqa.selenium.ie.InternetExplorerDriver;11import org.openqa.selenium.support.ui.ExpectedCondition;12import org.openqa.selenium.support.ui.ExpectedConditions;13import org.openqa.selenium.support.ui.WebDriverWait;14import java.util.Collections;15import java.util.Comparator;16import java.util.List;17import org.openqa.selenium.By;18import org.testng.Assert;19import MODEL.Product;20public class CommonBase {21	public void Click(WebElement element, WebDriver driver) {22		waitForPageLoaded(driver);23		element.click();24	}25	public void getURL(String url, WebDriver driver) {26		driver.get(url);27		pause(1000);28	}29	public void pause(long timeInMillis) {30		try {31			Thread.sleep(timeInMillis);32		} catch (InterruptedException e) {33			e.printStackTrace();34		}35	}36	public void setText(WebElement element, WebDriver driver, String value) {37		WebDriverWait wait = new WebDriverWait(driver, 10);38		try {39			if (element != null) {40				wait.until(ExpectedConditions.visibilityOf(element));41				element.clear();42				element.sendKeys(value);43			} else {44				wait.until(ExpectedConditions.visibilityOf(element));45				element.sendKeys(value);46			}47		} catch (StaleElementReferenceException e) {48			pause(1000);49			setText(element, driver, value);50		} catch (NoSuchElementException e) {51			pause(1000);52			setText(element, driver, value);53		} catch (ElementNotVisibleException e) {54			pause(1000);55			setText(element, driver, value);56		}57	}58	public void waitForPageLoaded(WebDriver driver) {59		ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {60			public Boolean apply(WebDriver driver) {61				return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString()62						.equals("complete");63			}64		};65		try {66			Thread.sleep(2000);67			WebDriverWait wait = new WebDriverWait(driver, 30);68			wait.until(expectation);69		} catch (Throwable error) {70			error.getCause().toString();71		}72	}73	public String getText(WebElement element) {74		try {75			return element.getText();76		} catch (StaleElementReferenceException e) {77			pause(1000);78			return getText(element);79		}80	}81	public Boolean verifyElementText(WebElement element, String text) {82		Boolean check = false;83		try {84			if (element.getText() == text) {85				check = true;86			}87		} catch (StaleElementReferenceException e) {88			pause(1000);89			return false;90		} 91		return check;92	}93	public String trimCharactor(String input, String trim) {94		if (input != "" && input != null && trim != "") {95			if (trim == ".") {96				return input.replaceAll("\\.", "");97			} else {98				return input.replaceAll(trim, "");99			}100		} else101			return "";102	}103	public WebElement getElement(String locator, WebDriver driver) {104		WebElement elem = null;105		try {106			elem = driver.findElement(By.xpath(locator));107		} catch (NoSuchElementException e) {108			getElement(locator, driver);109		} catch (StaleElementReferenceException e) {;110			getElement(locator, driver);111		}112		return elem;113	}114	public String getAttribute(WebElement element) {115		return element.getAttribute("href").toString();116	}117	public String getListAttribute(WebElement element) {118		return element.getAttribute("href").toString();119	}120	public List<WebElement> getListElements(String locator, WebDriver driver) {121		List<WebElement> elements = null;122		try {123			elements = driver.findElements(By.xpath(locator));124		} catch (NoSuchElementException e) {125			getElement(locator, driver);126		} catch (StaleElementReferenceException e) {;127			getElement(locator, driver);128		}129		return elements;130	}131	public void printList(List<Product> list) {132		for (Product pd : list) {133			System.out.println(pd.getWebsite() + "  Name: " + pd.getName() + "  Price: " + pd.getPrice()+ "   Link to detail:" + pd.getUrl());134		}135	}136	137}...Source:searchPage.java  
...18		//Checking every filters on the webpage19		driver.findElement(By.xpath(prop.getProperty("accreditedCheckbox_xpath"))).click();20		try {21			driver.findElement(By.xpath(prop.getProperty("open_24X7Checkbox_xpath"))).click();22		} catch (org.openqa.selenium.StaleElementReferenceException ex) {23			// TODO: handle exception24			driver.findElement(By.xpath(prop.getProperty("open_24X7Checkbox_xpath"))).click();25		}26		try {27			driver.findElement(By.xpath(prop.getProperty("all_filters_xpath"))).click();28		} catch (org.openqa.selenium.StaleElementReferenceException ex) {29			// TODO: handle exception30			driver.findElement(By.xpath(prop.getProperty("all_filters_xpath"))).click();31		}32		try {33			driver.findElement(By.xpath(prop.getProperty("Has_Parking_checkbox_xpath"))).click();34		} catch (org.openqa.selenium.StaleElementReferenceException ex) {35			// TODO: handle exception36			driver.findElement(By.xpath(prop.getProperty("Has_Parking_checkbox_xpath"))).click();37		}38		39		//ScreenShot and Extent Report40		screenshot("FiltersSeleted.png",driver);41		reportPass("Every Filters Executed");42		43		/****************************Printing All Hospitals having rating > 3.5**************************/44		45		System.out.println("****************Hospitals having rating greater than 3.5*********************");46		List<WebElement> hospitalsElements = driver.findElements(By.xpath(prop.getProperty("hospitalCard_xpath")));47		float rating;48		int n = hospitalsElements.size();49		for (int i = 1; i <= n-1; i++) {50			try {51				rating = Float.valueOf(driver.findElement(By.xpath(prop.getProperty("hospitalRating_xpath1") + i + prop.getProperty("hospitalRating_xpath2"))).getText());52			} catch (org.openqa.selenium.StaleElementReferenceException ex) {53				// TODO: handle exception54				rating = Float.valueOf(driver.findElement(By.xpath(prop.getProperty("hospitalRating_xpath1") + i + prop.getProperty("hospitalRating_xpath2"))).getText());55			}56			for(int trial = 0;trial<5;trial++) {57				try {58					if(!driver.findElement(By.xpath(prop.getProperty("hospitalRating_xpath1") + i + prop.getProperty("hospitalRating_xpath2"))).isDisplayed()) {59						continue;60					}61				} catch (org.openqa.selenium.StaleElementReferenceException ex) {62					// TODO: handle exception63					if(!driver.findElement(By.xpath(prop.getProperty("hospitalRating_xpath1") + i + prop.getProperty("hospitalRating_xpath2"))).isDisplayed()) {64						continue;65					}66				}67			}68			69			if (rating > 3.5) {70				String hospitalName;71				try {72					hospitalName = driver.findElement(By.xpath(prop.getProperty("hospitalName_xpath1") + i + prop.getProperty("hospitalName_xpath2"))).getText();73				} catch (org.openqa.selenium.StaleElementReferenceException ex) {74					// TODO: handle exception75					hospitalName = driver.findElement(By.xpath(prop.getProperty("hospitalName_xpath1") + i + prop.getProperty("hospitalName_xpath2"))).getText();76				}77				78				System.out.println(hospitalName);79			}80		}81		reportPass("All Hospitals having rating > 3.5 printed on console");82		83		//Click the diagnostics Button84		try {85			driver.findElement(By.xpath(prop.getProperty("diagnosticsButton_xpath"))).click();86		} catch (org.openqa.selenium.StaleElementReferenceException ex) {87			// TODO: handle exception88			driver.findElement(By.xpath(prop.getProperty("diagnosticsButton_xpath"))).click();89		}90		91		//Extent report submission92		reportPass("Diagnostics Page Executed");93		return PageFactory.initElements(driver, diagnosticsPage.class);94	}95}...Source:R12PayrollProcessingPage.java  
1package PageClasses;23import org.openqa.selenium.By;4import org.openqa.selenium.Keys;5import org.openqa.selenium.StaleElementReferenceException;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebElement;8import org.openqa.selenium.support.FindBy;9import org.openqa.selenium.support.PageFactory;10import org.openqa.selenium.support.ui.ExpectedConditions;11import org.openqa.selenium.support.ui.WebDriverWait;1213public class R12PayrollProcessingPage 14{15	WebDriver driver;16	17	@FindBy(xpath="//*[contains(@id,'if1::f')]")18	WebElement ProcessingMainFrame;19	20	@FindBy(xpath="//frame[@id='contentFrame']")21	WebElement ProcessingMainFrame2;22	23	@FindBy(name="compCode")24	WebElement PayrollCompanyBox;25	26	@FindBy(xpath="//*[contains(@id,'compName')]")27	WebElement PayrollCompanyDescBox;28	29	@FindBy(xpath="//*[contains(@id,'homeCompCode')]")30	WebElement HomeCompanyBox;31	32	@FindBy(xpath="//*[contains(@id,'homeCompName')]")33	WebElement HomeCompanyDescBox;34	35	@FindBy(xpath="//*[contains(@id,'prnCode')]")36	WebElement PayRunBox;37	38	@FindBy(xpath="//*[contains(@id,'prnName')]")39	WebElement PayRunDescBox;40	41	@FindBy(xpath="//*[contains(@id,'pprYear')]")42	WebElement PayYearBox;43	44	@FindBy(xpath="//*[contains(@id,'pprPeriod')]")45	WebElement PayPeriodBox;46	47	@FindBy(xpath="//*[contains(@id,'processPayrollButton')]")48	WebElement ProcessButton;49	50	public R12PayrollProcessingPage(WebDriver driver)51	{52		this.driver=driver;53		PageFactory.initElements(driver, this);54	}55	56	public void switchToMainFrame()57	{	58		new WebDriverWait(driver,20).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(ProcessingMainFrame));59		new WebDriverWait(driver,20).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(ProcessingMainFrame2));60	}61	62	public void enterPayrollCompany(String company)63	{	64		new WebDriverWait(driver, 20).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(PayrollCompanyBox));65		PayrollCompanyBox.sendKeys(company);66		PayrollCompanyBox.sendKeys(Keys.TAB);67		new WebDriverWait(driver, 20).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.textToBePresentInElement(PayrollCompanyDescBox,""));68	}69	70	public void enterHomeCompany(String company)71	{72		HomeCompanyBox.sendKeys(company);73		HomeCompanyBox.sendKeys(Keys.TAB);74		new WebDriverWait(driver, 20).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.textToBePresentInElement(HomeCompanyDescBox,""));75	}76	77	public void enterPayRun(String payrun)78	{79		PayRunBox.sendKeys(payrun);80		PayRunBox.sendKeys(Keys.TAB);81		new WebDriverWait(driver, 20).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.textToBePresentInElement(PayRunDescBox,""));82	}83	84	public void enterPayYear(String year)85	{86		PayYearBox.sendKeys(year);87		PayYearBox.sendKeys(Keys.TAB);88	}89	90	public void enterPayPeriod(String period)91	{92		PayPeriodBox.sendKeys(period);93		PayPeriodBox.sendKeys(Keys.TAB);94	}95	96	public void clickProcessButton()97	{98		ProcessButton.click();99		new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.alertIsPresent());100		101	}102}
...Source:FluentWaitConcept.java  
1package seleniumSessions;2import java.time.Duration;3import java.util.NoSuchElementException;4import org.openqa.selenium.By;5import org.openqa.selenium.StaleElementReferenceException;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebElement;8import org.openqa.selenium.chrome.ChromeDriver;9import org.openqa.selenium.support.ui.ExpectedConditions;10import org.openqa.selenium.support.ui.FluentWait;11import org.openqa.selenium.support.ui.Wait;12import org.openqa.selenium.support.ui.WebDriverWait;13import io.github.bonigarcia.wdm.WebDriverManager;14public class FluentWaitConcept {15	public static WebDriver driver;16	17	public static void main(String[] args) {18	19		WebDriverManager.chromedriver().setup();20		driver = new ChromeDriver();21		22		driver.get("https://demo.opencart.com/index.php?route=account/login");23		24		By emailId = By.id("input-email1");25		By password = By.id("input-password");26		27//		Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)28//								.withTimeout(Duration.ofSeconds(10))29//								.pollingEvery(Duration.ofSeconds(2))30//								.ignoring(NoSuchElementException.class)31//								.ignoring(StaleElementReferenceException.class);32//33//		wait.until(ExpectedConditions.visibilityOfElementLocated(emailId)).sendKeys("test@123");34		35		waitForElementVisibleWithFluentWait(emailId, 10, 2).sendKeys("testing@123");36		driver.findElement(password).sendKeys("123");37		38	}39	40	public static WebElement waitForElementVisibleWithFluentWait(By locator, int duration, int pollingTime) {41		Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)42				.withTimeout(Duration.ofSeconds(duration))43				.pollingEvery(Duration.ofSeconds(pollingTime))44				.ignoring(NoSuchElementException.class)45				.ignoring(StaleElementReferenceException.class)46				.withMessage(locator + " is not found within the given time ....");47		return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));48	}49	50	public static WebElement waitForElementPresenceWithWait(By locator, int duration, int pollingTime) {51		52		WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(duration));53		54		wait.pollingEvery(Duration.ofSeconds(pollingTime))55			.ignoring(NoSuchElementException.class)56			.ignoring(StaleElementReferenceException.class)57			.withMessage(locator + " is not found within the given time ....");58		59		return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));60		61		62	}63}StaleElementReferenceException
Using AI Code Generation
1import org.openqa.selenium.StaleElementReferenceException;2import org.openqa.selenium.support.ui.WebDriverWait;3import org.openqa.selenium.support.ui.ExpectedCondition;4import org.openqa.selenium.By;5import org.openqa.selenium.NoSuchElementException;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebElement;8import org.openqa.selenium.chrome.ChromeDriver;9import java.util.concurrent.TimeUnit;10import java.lang.System;11{12    public static void main(String[] args)13    {14        WebDriver driver = new ChromeDriver();15        driver.manage().window().maximize();16        driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);17        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);18        driver.findElement(By.cssSelector("button[onclick='showInput();']")).click();19        WebDriverWait wait = new WebDriverWait(driver, 10);20        ExpectedCondition<WebElement> condition = new ExpectedCondition<WebElement>()21        {22            public WebElement apply(WebDriver driver)23            {24                WebElement element = driver.findElement(By.id("display"));25                if (element.isDisplayed())26                {27                    return element;28                }29                {30                    return null;31                }32            }33        };34        wait.until(condition);35        System.out.println("Text message is displayed");36        driver.close();37    }38}StaleElementReferenceException
Using AI Code Generation
1    public class StaleElementReferenceExceptionExample {2        public static void main(String[] args) {3            System.setProperty("webdriver.chrome.driver", "C:\\Users\\gaurav\\Downloads\\chromedriver_win32\\chromedriver.exe");4            ChromeOptions options = new ChromeOptions();5            options.addArguments("--disable-notifications");6            WebDriver driver = new ChromeDriver(options);7            driver.manage().window().maximize();StaleElementReferenceException
Using AI Code Generation
1package com.selenium;2import org.openqa.selenium.By;3import org.openqa.selenium.NoSuchElementException;4import org.openqa.selenium.StaleElementReferenceException;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.WebElement;7import org.openqa.selenium.chrome.ChromeDriver;8public class StaleElementReferenceExceptionDemo {9	public static void main(String[] args) throws InterruptedException {10		System.setProperty("webdriver.chrome.driver", "C:\\Users\\hp\\Desktop\\chromedriver.exe");11		WebDriver driver = new ChromeDriver();12		driver.manage().window().maximize();13		element.click();14		Thread.sleep(3000);15		driver.navigate().back();16		Thread.sleep(3000);17		try {18			element.click();19		} catch (StaleElementReferenceException e) {StaleElementReferenceException
Using AI Code Generation
1import org.openqa.selenium.StaleElementReferenceException;2import org.openqa.selenium.WebElement;3import org.openqa.selenium.support.ui.ExpectedConditions;4import org.openqa.selenium.support.ui.WebDriverWait;5import org.testng.annotations.Test;6import org.testng.asserts.SoftAssert;7public class StaleElementReferenceExceptionDemo extends BaseClass{8public void testStaleElementReferenceException() {9SoftAssert softAssert = new SoftAssert();10inputFormsLink.click();11simpleFormDemoLink.click();12WebDriverWait wait = new WebDriverWait(driver, 20);13enterMessageTextbox.sendKeys("Hello");14showMessageButton.click();15softAssert.assertEquals(yourMessageLabel.getText(), "Hello");16driver.navigate().back();17try {18inputFormsLink.click();19}catch(StaleElementReferenceException e) {20inputFormsLink.click();21}22simpleFormDemoLink.click();23wait = new WebDriverWait(driver, 20);24enterMessageTextbox.sendKeys("Hello");25showMessageButton.click();26softAssert.assertEquals(yourMessageLabel.getText(), "Hello");27softAssert.assertAll();28}29}StaleElementReferenceException
Using AI Code Generation
1import org.openqa.selenium.StaleElementReferenceException;2public class StaleElementReferenceExceptionDemo {3    public static void main(String[] args) {4        WebDriver driver = new FirefoxDriver();5        WebElement searchBox = driver.findElement(By.name("q"));6        searchBox.sendKeys("Selenium");7        driver.findElement(By.name("btnG")).click();8        try {9            driver.findElement(By.name("btnG")).click();10        } catch (StaleElementReferenceException e) {11            System.out.println("Element is not attached to the page document "+ e.getStackTrace());12        }13        driver.quit();14    }15}16public StaleElementReferenceException(String message)17public StaleElementReferenceException(String message, Throwable cause)18public StaleElementReferenceException(Throwable cause)19public String getMessage()20public Throwable getCause()21public StackTraceElement[] getStackTrace()22public String toString()23public void printStackTrace()24public void printStackTrace(PrintStream stream)25public void printStackTrace(PrintWriter writer)26public synchronized Throwable fillInStackTrace()27public Throwable initCause(Throwable cause)28public String getLocalizedMessage()29public synchronized Throwable getCause()30public Throwable initCause(Throwable cause)31public String getMessage()32public String getLocalizedMessage()33public StackTraceElement[] getStackTrace()34public void setStackTrace(StackTraceElement[] stackTrace)35public String toString()36public void printStackTrace()37public void printStackTrace(PrintStream s)38public void printStackTrace(PrintWriter s)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!!
