37078

StaleElementReferenceException when trying to click on the links in a loop

Question:

<a href="https://i.stack.imgur.com/bSaNU.jpg" rel="nofollow">Please click on the link below to see the link <strong>"BEAUTY"</strong> on which I am clicking </a> 1. I am using this code to click on the "Beauty" link

driver = webdriver.Chrome("C:\\Users\\gaurav\\Desktop\\chromedriver_win32\\chromedriver.exe") driver.maximize_window() driver.get("http://shop.davidjones.com.au") object = driver.find_elements_by_name('topCategory') for ea in object: print ea.text if ea.text == 'Beauty': ea.click() <ol start="2"><li>

I am getting the following exceptions after clickin on the link succesfully , can anybody tell me why I am getting it ?

Traceback (most recent call last): File "C:/Users/gaurav/PycharmProjects/RIP_CURL/login_raw.py", line 10, in <module> print ea.text File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 73, in text return self._execute(Command.GET_ELEMENT_TEXT)['value'] File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 493, in _execute return self._parent.execute(command, params) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document (Session info: chrome=63.0.3239.132) (Driver info: chromedriver=2.34.522940 (1a76f96f66e3ca7b8e57d503b4dd3bccfba87af1),platform=Windows NT 6.2.9200 x86_64) </li> </ol>

Answer1:

Try this:

from selenium import webdriver print("bot started") #chromeOptions = webdriver.ChromeOptions() #driver = webdriver.Chrome(chrome_options=chromeOptions) def specific_text(text, ea): return str(text) == ea.text driver = webdriver.Chrome("C:\\Users\\gaurav\\Desktop\\chromedriver_win32\\chromedriver.exe") driver.maximize_window() driver.get("http://shop.davidjones.com.au") object_ = driver.find_elements_by_name('topCategory') text_headers = [str(specific_text('Beauty', ea)) for ea in object_] #print(text_headers) index_text = text_headers.index("True") #print(index_text) object_[index_text].click()

Answer2:

You need to take care of certain factors as follows :

<ul><li>You have tried to create a List by the name <strong>object</strong>. <strong>object</strong> is a <strong>reserved built-in symbol</strong> in most of the Programming Languages. So as per Best Programming Practices we shouldn't use the name <strong>object</strong>.</li> <li>The line <strong>print ea.text</strong> is badly indented. You need to add indentation.</li> <li>Once you invoke click() on the WebElement with text as <strong>Beauty</strong> you need to <strong>break</strong> out of the loop.</li> <li>

Here is your own working code with some minor tweaks :

from selenium import webdriver driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe') driver.maximize_window() driver.get("http://shop.davidjones.com.au") object1 = driver.find_elements_by_name('topCategory') for ea in object1: print (ea.text) if ea.text == 'Beauty': ea.click() break </li> <li>

Console Output :

Sale Brands Women Men Shoes Bags & Accessories Beauty </li> </ul>

Answer3:

There's an easier way to do this. You can use an XPath that will specify the category name you want to click. That way you don't have to loop, it will find the desired element in one search.

//span[@name='topCategory'][.='Beauty']

I'm assuming you will be reusing this code. In cases like this, I would create a function that takes a string parameter which would be the category name that you want to click. You feed that parameter into the XPath above and you can then click any category on the page.

I tested this and it's working.

Recommend

  • ImportError: No module named 'fabric.contrib'
  • I can open a jupyter notebook, but I cannot run the notebook with python script in it on my Mac
  • PDO via SSH2 in PHP?
  • python selenium selenium.common.exceptions.StaleElementReferenceException error
  • mvvm confusion with canexecute and binding commands
  • How to click on an element before the page is fully loaded i'm stuck, it takes too much time un
  • How to control the newly opened window that appears after a click in Selenium WebDriver?
  • WebElement.clear() fires javascript change event - Alternatives?
  • How to start appium test on iOS simulator?
  • How to parse Selenium driver elements?
  • Showing spinner for Rails 3 UJS gets Type error
  • Can my app be notified when another application starts/stops playing audio?
  • Aptana 3 remove bundle (jquery)
  • Magento site down due to mysql error General error: 1030 Got error -1 from storage engine
  • How can I run DataNucleus Bytecode Enhancer from SBT?
  • How to get links to open in the native browser in iOS Meteor apps?
  • How can I replace the server in Web Component Tester
  • aapt.exe'' finished with non-zero exit value 1
  • How to install node-mysql?
  • Suppressing passwd when calling sqlplus from shell script
  • Security issues with PHP's Readfile method
  • Check for zero lines output from command over SSH
  • Run multiple queries from 1 SQL file showing result in multiple tables
  • Copy to all folders batch file?
  • onBackPressed() not being executed
  • Make VS2015 use angular-cli ng at build time in a .NET project
  • SignalR .NET Client Invoke throws an exception
  • Jenkins: How To Build multiple projects from a TFS repository?
  • Azure Cloud Service Web Role web pages do not load
  • How do I fake an specific browser client when using Java's Net library?
  • Delete MySQLi record without showing the id in the URL
  • Apache 2.4 - remove | delete | uninstall
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • coudnt use logback because of log4j
  • Is there any way to bind data to data.frame by some index?
  • Django query for large number of relationships
  • Programmatically clearing map cache
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?