Unable to cycle through various categories by clicking in order to navigate to the desired page

After creating a Python script using Selenium to click through various categories on a website and reach the target page, I encountered an issue. The script works once but throws a 'stale element' error when trying to repeat the process. How can I address this to ensure continued success?

Here is a snippet of my current attempt:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = "https://www.courts.com.sg/"

def get_information(driver,mlink):
    driver.get(mlink)
    # Click on the menu
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'span.nav-toggle'))).click()
    # Click on individual categories
    for item in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,'#menu-top1535320854159022796-menu .nav-anchor .opener'))):
        item.click()
        # Click on sub-categories
        for link in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.nav-dropdown h3 a'))):
            link.click()
            # Click on target items
            for ilink in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,'li.show a')))[1:]:
                ilink.click()
                # Issue arises here with 'stale element error' preventing repeat process


if __name__ == '__main__':
    driver = webdriver.Chrome()
    wait = WebDriverWait(driver,10)
    try:
        get_information(driver,url)
    finally:  
        driver.quit()

Answer №1

If you encounter a stale element error, it could be due to the menu opening when hovered over and disappearing when clicked on inside your loops.
Here are two solutions to consider:

def get_information(driver,mlink):
    driver.get(mlink)
    submenu_links = []
    submenus = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.submenu li a')))
    for submenu in submenus:
        submenu_links.append(submenu.get_attribute("href"))

    for link in submenu_links
        driver.get(link)

In case you need to open the menu:

def get_information(driver,mlink):
    driver.get(mlink)
    
    menus = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,'.navigation li.nav-item')))
    for menu in menus:

        ActionChains(driver).move_to_element(menu).perform()

        submenu_links = []
        submenus = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.submenu li a')))
        for submenu in submenus:
            submenu_links.append(submenu.get_attribute("href"))

        for link in submenu_links
            driver.get(link)

Answer №2

Here's an alternative method to tackle the issue...(I avoid using CSS selectors :))

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
from bs4 import BeautifulSoup

url_list = []
url = "https://www.courts.com.sg/"
def get_data(driver,mlink):
    driver.get(mlink)
    sleep(5)
    soup = BeautifulSoup(driver.page_source)
    uls = soup.find_all('ul', {'class': 'nav-mobile'})
    for li in uls[0].find_all('li', {'class': 'nav-item'}):
        submenu = li.find_all('div', {'class':'nav-dropdown'})
        uls = submenu[0].find_all('ul')
        for ul in uls:
            all_li = ul.find_all('li')
            for i in range(1,len(all_li)):
                a = all_li[i].find_all('a')
                print(a)
                a = 'https://www.courts.com.sg' + a[0].get('href')
                url_list.append(a)

if __name__ == '__main__':
    driver = webdriver.Chrome('C:/Users/sarthak_negi_/Downloads/chromedriver_win32/chromedriver.exe')
    wait = WebDriverWait(driver,10)
    try:
        get_data(driver,url)
    finally:  
        driver.quit()

The list of URLs is stored in url_list and you can access each page by doing a GET request on them. I hope this solution proves helpful!

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

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

Having difficulty executing the Switch Browser Command on Robot Framework

I am facing an issue in my test scenario where I need to open two browsers and switch to the first browser that was opened. However, the command to switch browsers is not functioning as expected. Although no errors are generated, the browser does not actua ...

Getting started with Codeception may not always be straightforward: [PHPUnitFrameworkException] Error encountered - Element index not defined

After following the Codeception Quick Start instructions diligently, I proceeded to run the initial example test using PhpBrowser... # Codeception Test Suite Configuration # # [further comments omitted] # actor: AcceptanceTester modules: enabled: ...

Obtain the MAC address of a host from within a containerized environment

Is there a way to retrieve the MAC address of the host within a docker container without using the host network or setting it as an ENV variable? Ideally, I am looking for a solution involving a program written in C++ or Python that can run inside the do ...

Exception encountered: The 'IntegerField' object does not possess the attribute 'max_length'

I have not set any restrictions on the IntegerField regarding max_length, so I am unsure about the issue at hand. Below is the code snippet from models.py. Can you please advise on what additional information I should provide to gain a better understanding ...

What reasons could cause genguid.exe to fail to work with generated clsid?

I have been attempting to tweak the exceladdin.py example from the pywin demos. Whenever I try to replace the clsid provided in the example with one generated by genguid.exe or pythoncom.CreateGuid() like this: "{E44EF798-7FDF-4015-AED6-00234CBBBA77}" T ...

The playwright encounters difficulty launching Chrome in an Alpine Docker environment

I've encountered an error while running a scrapper (a nodejs application) on node:lts-alpine within a docker container. INFO PlaywrightCrawler: Initiating the crawl WARN PlaywrightCrawler: Attempting to reclaim failed requests by adding them back to ...

What is the method for incorporating a run_date into the code for my Airflow Dag?

Just starting out with Python and I'm wondering how to give my table a name that includes the date. Anyone have any suggestions? with DAG("inform_status", schedule_interval="55 17 * * 1-5", start_ ...

Selenium halts the processing of requests

After extracting option IDs from the html file in previous operations, I will store them into a list. Next, I will iterate through each element in the list and attempt to open a page like: www.xxx.xxx/en/account/service/SERVICEID Upon successfully openin ...

Different ways to classify or organize selenium webdriver tests

Imagine a scenario where a webpage contains numerous links and buttons that execute JavaScript functions. The question arises: should each link and button have its own Java test class, or should all the links be tested in one method and other elements in a ...

Can you provide guidance on the correct syntax for sending a JSON post request to StubHub?

{ "listing":{ "deliveryOption":"option", "event":{ "date":"date", "name":"name of event", "venue":"venue" }, "externalListingId":"000000000", "inhandDate":"inhand date", "pricePerTicke ...

I'm receiving an error stating "unsupported operand type(s) for +: 'int' and 'tuple'." What steps can I take to resolve this problem?

Upon executing the code below, I encountered an error with this specific line of code tem=p.gamma_dB_min+p.delta_dB_gam*y. Can anyone help me resolve this issue? Thank you. def lin_interp(p,y1,yn): N = 28 n = np.arange(1,N) y = ( [y1 + (yn-y1)/ ...

Error Alert: Unable to import PerfectoLibrary due to import error

I am encountering an issue when trying to import the PerfectoLibrary. The error message I receive is: [ ERROR ] Error in file 'C:\Pipelines\obrexternal-testautomation\OBRRobotFramework_Mobile\Resources\common\OBRKeywords_ ...

Error Encountered: Unable to open the specified URL using Selenium code

I'm experiencing an issue where the browser opens but the URL is not getting typed by the script. Can someone please provide suggestions on how to correct this script? package SeleniumDemo; import java.util.concurrent.TimeUnit; import org.openqa.sel ...

I am having trouble navigating between windows using the window name (driver.switchTo("windowName"))

While conducting a test, I encountered an issue where I was unable to switch to a specific window by its name. In the scenario, there are three open windows, with the only distinguishing factor being that the window I needed to access contained a hyphen ...

Encountering authentication issues with Python Requests, receiving a 405 error alongside the AttributeError: 'unicode' object does not have the attribute 'items'

Attempting to utilize the Python "requests" module to access SECURE NIFI rest API (https://nifi.apache.org/docs/nifi-docs/rest-api/), I have encountered two issues thus far: When trying to use basic and digest authentication methods provided by the "requ ...

Pop-up warning - endless search cycle

As a novice, my question might be a bit strange :) I want to test the Main Menu of the website "https://tvn24.pl/" I am searching for elements, adding them to a list, and then iterating through each one to open every discovered page - everything is worki ...

Issue with unnamed column in Pandas dataframe prevents insertion into MySQL from JSON data

Currently, I am working with a large JSON file and attempting to dynamically push its data into a MySQL database. Due to the size of the JSON file, I am parsing it line by line in Python using the yield function, converting each line into small pandas Data ...

Building a bespoke neural network structure with Pytorch

Exploring the creation of a personalized CNN structure with Pytorch but aiming for a level of control similar to what I could achieve using numpy exclusively. Seeking assistance as a beginner in Pytorch and interested in viewing examples of CNNs developed ...

Tips on saving mouse button choices in a list?

While experimenting, I attempted to develop an interactive version of the mastermind game in Python using Pygame. Essentially, the CPU will generate a random list of tuples (4 in length), where each tuple represents an RGB combination (e.g. [(255,0,0), (13 ...