Using Selenium with Python: Overcoming StaleElementReferenceException when selecting by class

Attempting to create a basic Python script using Selenium, I encountered a StaleElementReferenceException after the loop runs once.

Check out the code snippet being executed:

from selenium import webdriver

browser = webdriver.Firefox()
type(browser)
browser.get('http://digital2.library.ucla.edu/Search.do?keyWord=&selectedProjects=27&pager.offset=50&viewType=1&maxPageItems=1000')
links = browser.find_elements_by_class_name('searchTitle')

for link in links:
    link.click()
    print("clicked!")
    browser.back()

As an attempted solution, I added browser.refresh() within the loop but unfortunately, it did not resolve the issue.

I'm fairly new to this, so please be patient and refrain from bombarding me with criticisms.

Answer №1

Avoid clicking through links within a loop as it can lead to navigation issues. Once you click on a link, you navigate away from the page containing the links. Does that concept make sense to you?

To address this, remove the for loop and consider something like link = links[0] to select the first link or a more specific method to target the desired link accurately.

If your goal is to click on every link present on the page, you can utilize the following approach:

links = browser.find_elements_by_class_name('searchTitle')
for i in range(len(links)):  
    links = browser.find_elements_by_class_name('searchTitle')
    link = links[i]  # selecting the i'th link on the page
    link.click()
    print("clicked!")
    browser.back() 

UPDATE: Enhancing the script might involve adding a pause after calling `browser.back()`. This can be achieved by inserting the following code snippet:

from time import sleep 
...
sleep(5) # defining a 5-second pause

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining a series of coordinates from a Numpy array

I have a 100x100x100 numpy array that represents a 3D volume composed of 2D slices. My goal is to conduct cross correlation on the object in this volume across multiple volumes using a template derived from the volume with the best signal-to-noise ratio. ...

Exploring the capabilities of Selenium 4 for adjusting column sizes in C#

In my website testing, I have been using Selenium 3.141 and now want to upgrade to the latest version, Selenium 4.4. However, I am facing issues with resizing columns in a table due to changes in Selenium Actions. Below is the code that worked for me in S ...

Combine data in PySpark by matching multiple keys while keeping only one copy of columns with distinct names

I need to perform an outer join on two dataframes using Spark: Dataframe 1 columns: first_name, last, address Dataframe 2 columns: first_name, last_name, phone_number The keys for joining are first_name and df1.last==df2.last_name The desired schema fo ...

Is it possible to verify and access a downloaded file using Selenium?

My task involves checking a downloaded PDF and opening it using Selenium. To achieve this, I am utilizing the Robot class. However, this method is not a permanent or general solution. Query: Could someone assist in providing a more reliable solution for t ...

What could be causing my code to only recognize the first condition and overlook the second one?

Can someone help me understand why my code is only evaluating the first condition and not checking for the second condition as well? def identifyWeapon(): if keyPress.positive: if raySensor.hitObject['primaryWeapon']: ...

What is the best method to ensure that Selenium WebDriver waits for an AJAX load to complete before proceeding with any

Is there a way to ensure that Selenium WebDriver waits for an Ajax load before proceeding with any activities? I am automating the process of filling out a form using my script, where I click on a button that opens a new form with some fields prepopulated ...

I keep encountering the error message "The method timeouts() isn't recognized within the WebDriver.Options type"

I have implemented my implicit wait as shown in the code snippet below: //import import org.openqa.selenium.WebDriver; //driver declaration public static WebDriver driver = null; //implicit wait driver.manage().timeouts().implicitlyWait(30, TimeUnit.SE ...

Retrieving data in JSON format from an API and converting it into a more usable JSON format using Flask

How can I convert data from JSON format into a web application using Flask to populate values in HTML? Here is the code in spec_player.html: {% for p in posts: %} <p>{{p.first_name}}</p> {% endfor %} This method works (main.py): posts = ...

Searching for an HTML element within another using selenium

Is there a way to use the list of elements I obtained with find_elements method in a for loop to search for elements containing a specific string and ensure they each contain a span with certain text? today = self.dataBrowser.find_elements(By.XPATH, f&apos ...

Element cannot be located using XPath Selector for a text type without a corresponding name or Id

Browser Inspection Tool https://i.stack.imgur.com/jsOeJ.png An Example in C# IWebElement Search = driver.FindElement(By.XPath("//*[@placeholder='search' and @type='text']")); Actions actions_Search = new Actions ...

Combine CSV files and set column assignments

Currently, I am utilizing Python to iterate through a list of CSV files (stored locations in the dataframe) and merge them into one central dataframe. The script is almost complete, but I encounter issues when trying to add a column to each individual data ...

Struggling with installing fiona and geopandas on Python in Windows 10? Encounter the frustrating "can't load requested DLL" error? Let us guide

I'm currently attempting to install fiona and geopandas for Python on a Windows 10 system, but encountering an error that reads "ERROR 1: Can't load requested DLL". Despite following various answers and tutorials on this issue, I still can' ...

Iterating through a list in Python to check if an item exists in a line

I need to iterate through two lists and only print an item if it is present in the second list. However, I am working with very large files and do not want to load them into memory as a list or dictionary. Is there a method to achieve this without storing ...

Can messages be transmitted to Log Stream (App Insights Logs) within Azure Function App?

I've been searching for a solution, but have yet to find one. When I'm in my Function App, I go here: https://i.stack.imgur.com/9kwC2.png Then click the drop-down arrow and choose Application Insight Logs https://i.stack.imgur.com/s4Chu.png ...

Exploring the integration of automation with the "Windows authentication dialog" to effortlessly log into a web application using C#, Selenium WebDriver

Struggling to log in to the web application using the Windows authentication popup. Attempted to switch windows with “driver.SwitchTo().Alert()” and even used “driver.get(“http//user:[email protected]”)”, but nothing seems to be effectiv ...

What steps should I take to resolve the "Error: Failed to establish a new connection [Errno 10061]" issue in my python code?

I'm having issues running my Python script as it keeps displaying the same error message: Failed to establish a new connection: [Errno 10061] No connection could be made because the target machine actively refused it. Note that I have disabled my f ...

Exploring selenium for automating tests on a Facebook Messenger bot. Tips for efficiently identifying user input and bot responses within the chat interface

We are currently working on automating the testing process of a Facebook Messenger bot by using Selenium. Our main challenge is locating the messenger's text box using XPath, but unfortunately, we have been unsuccessful so far. Below is the snippet ...

A guide to pasting copied text from the clipboard using Selenium and Java on a Mac operating system

Having trouble pasting text into a textbox on MACOS? Trying to use the code snippet below, but Control + v and Command + v shortcuts are not working. It seems like this is a known issue, but unsure if it has been resolved yet. https://github.com/seleniumhq ...

Selenium Issue: Checkbox refuses to be ticked

Encountering an issue when trying to select a checkbox, receiving an 'OpenQA.Selenium.ElementNotVisibleException' exception. DOM Structure (consists of multiple rows each with a checkbox): <td style="text-align:center"> <input type ...

The execution of the selenium script is unreliable

Recently, I created a selenium script to automate certain manual checks on http:obsessory.com. The script utilizes a looping concept, such as mouse hovering over the Top menu and clicking on various submenus. However, during testing, I have encountered spo ...