How to solve selenium exception: StaleElementReferenceException: Element not found in the cache - selenium

I'm getting collection of links. Then I click first link, do something, moving back (driver.navigate().back();), getting second link and then link.click(); throws an exception org.openqa.selenium.StaleElementReferenceException: Element not found in the cache.
What am I doing wrong?

As soon as you navigate away from the page the element variables become invalid. The trick is to find the first element, click, go back and then find the second element and click.

Related

Trouble getting an element to be clicked using Selenium

I am trying to go to the below URL
https://twitter.com/explore
Enter HBO Max in the text box which I locate using
By.cssSelector("input[placeholder='Search Twitter']")
and then I want to select the HBO Max option that appears in the dropdown. My locator for the element to be selected is
By.xpath("//div[#role='option']//li/div/div[2]")
Sometimes the element gets clicked and I go to the new page, sometimes not. I have in my framework waited for the element to be clickable using WebDriverWait. The element is both visible and enabled because I print these values before I click the element.
Additional debugging steps performed -
Click using JavaScript seems to have the same behavior.
I believe I am using the right locator because the mouse event gets generated for this element.
Thread.Sleep seems to work suggesting that perhaps a timing issue
Any inputs would be great.
try:
myElem = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, 'ID')))
print("Page is ready!")
except TimeoutException:
print("Loading took too much time!")
Try this !
what it does : It wait until the specific element of the site is loaded. If it takes more time than specified will just give you an output as "loading took too.........."
You can modify the time required to wait.

stale element reference error after self.driver.back()?

I'm getting Selenium exception stale element reference: element is not attached to the page document after the first iteration of the for loop. My code is :
for gc in grpCommune:
self.driver.execute_script("return arguments[0].scrollIntoView(true);", gc)
self.driver.execute_script("window.scrollTo(0, 0);")
e=gc.find_element_by_xpath('//a[2]')
e.click()
sleep(1)
...
genertaeCSV()
self.driver.back()
how can I resolve it?
Stale Element exception occurs when the selenium reference bound to the element is no more valid, generally, this happens when you either navigate away from the page or refresh the page or the contents on the page is reloaded. In your case, you are trying to refer to the gc element which was captured with a reference before clicking the e element. The moment you clicked on e element using e.click() button, all the references in grpCommune is no longer valid. So, you will be able to run only the first iteration successfully with your code.
How do I fix this code:
Get the gc element within the for loop. Rather than using for each use for loop with the index.
Stale element exception occuring when element in on page but selenium driver instance could not interect with that element.
Following actions can be resolve stale element exception
1.Refresh page by using "navigate(). refresh()" method in selenium
2.using loop try to click or check visible of that element if that element visible or already clicked exit from loop.

Selenium cssselector shows correct webelement but script always run exception no such element

I got stuck not just for this one case. Many cases came out with nosuchelement exception, I cannot find the reason why. I use chrome console to locate the element and it shows correct result. Is that possible something wrong with the page itself, not my script?
Context click on the element you are trying to click, and see if the element is inside any frame. Try to navigate through the tags and see if this element is under any iframe.
switch to the iframe using,
driver.switchTo().frame(driver.findElement(By.xpath("iframexpath")));

Click method is not working when using JavascriptExecutor in Selenium

I am clicking on the text box displayed on first page
WebElement txtBox = driver.findElement(By.xpath("---xpath---"));
txtBox.click();
Then after some block of execution I am getting the same textbox in new page on same window.
Here also I want to click on the text box.
I used JavascriptExecutor to do this scripting.
((JavascriptExecutor)driver).executeScript("arguments[0].click();", txtBox );
But while running the script I am getting an error message saying:
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
You need to execute driver.findElement() every time you reload the page.
This method returns WebElement which is integral part of current page. If you refresh browser or navigate to some other URL or even if element is deleted and attached again by some javascript on same page, previously found element cannot be used anymore.
Here you have official explanation of this exception: http://www.seleniumhq.org/exceptions/stale_element_reference.jsp
Stale Element exception comes after you want to interact with an element loaded previously. If you get webelement and then reload the page it gives this exception because it is not in a newly created page. It is better to click the web element without assigning it to a variable like:
driver.findElement(By.xpath("---xpath---")).click();

selenium invalid element state: Element is not currently interactable and may not be manipulated

I have this issue with selenium; I cannot find i textinput : it always raises this exeception:
Element is not currently interactable and may not be manipulated
in this line:
Driver.FindElement(By.Id("ctl00")).Clear();
I try to put waiting like this:
Waiting.Until(driver =>(By.Id("ctl00")));
and
Waiting.Until(ExpectedConditions.ElementExists(By.Id("ctl00")));
but no luck.
If the exception gets thrown on Clear(),
the element is most likely present on the page and the input in a readonly state.
Try to validate XPath first as might be that targeting more than one element.
Due to this, element not currently interactable and may not be manipulated.
I faced same issue and found solution with above as my XPath was locating multiple element which exists on DOM but not page.
Correct the element XPath, error will resolve automatically with adding webdriver wait.
I hit the same error, was also a bit confused, but resolved it using the below wait condition. The elementToBeClickable condition checks that the element is both visible and enabled. Perhaps visibility is enough, but Selenium throws an explicit ElementNotVisibleException, so I'm not sure why I wouldn't get that...
Anyways, I opted to use a more robust wait condition, and it has worked well for me.
wait.until(ExpectedConditions.elementToBeClickable(By.id("myElementId"))).clear();
This happens sometimes when element is not visible. It would happen even when element is visible also.
Try using with different tags like xpath or etc.
You can check the element status using below script
driver.findElement(By.className("")).isEnabled()
It is due to element not visible so apply more wait while performing the action or you can use hardcoded sleep cause sometimes webdriver's wait doesn't work.
You are trying to perform .clear() on a WebElement, which is not an input tag. For example, if you try to do clear on a Span WebElement, You will get Selenium Invalid Element State error.
Waiting.Until(ExpectedConditions.ElementExists(By.Id("ctl00"))); should work.
Set break point at Waiting.Until() line and input $$("#ctl00") in Chrome console to check if the element is existing.
Make the driver to wait until an element is visible.
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(ExpectedConditions.visibilityOf(element));
Hope this helps!
If waiting for visibilityOf(), elementToBeClickable(), element.isEnabled() doesn't do the trick, try to look at the attributes of your element.
It may have some attributes responsible for read only state, in my case this was aria-readonly and aria-disabled, Hence I created custom wait like this:
webDriverWait.until(webDriver -> webElement.getAttribute("aria-readonly").equals("false") && webElement.getAttribute("aria-disabled").equals("false"));
Use this you will not get this error(might be scroll is not working here so use keypad TAB to move on, my problem got resolved by this)
Actions act = new Actions(driver);
act.sendKeys(Keys.TAB).build().perform();
act.sendKeys(Keys.RETURN).build().perform();
You might be asking an element with the same attribute like duplicate id, name etc.
I My case i was entering password in confirm password TextBox whose Id was "confirmPassword" but the same Id is used for the "Confirm Password" label for that TextBox.
So selenium was trying to perform sendKeys on the label instead of TextBox so getting "InvalidElementStateException", After that i changed the xpath and it worked.
So when you get "InvalidElementStateException" you should first check whether there are any duplicate element available with the xpath you have generated, and that not-interactive element could be a Button, Label or disabled element that causes the exception occurred.
I was clicking on a div element or label to element to clear the text in input tag. Changed my xpath to input tag and then I did not received any exception and the test was clear.