0

I'm trying to automate our testing for a website that has individual pages for each location.

This is the code I have tried but it is giving me a stale element error (Message: stale element reference: element is not attached to the page document).

The concept is this: Open the store directory page -> Click on the state -> Click on the cities in that state -> click on the stores in that city -> repeat

Here is the code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

url = 'https://example.com'

driver.get(url)

print(driver.title)

time.sleep(5)

states = ['Alaska', 'Arizona', 'California']

# - clicking on the state
for state in states:
    search_states = driver.find_element_by_link_text(state)
    search_states.click()
    time.sleep(2)

    # - click on the city
    search_cities = driver.find_elements_by_class_name('Directory-listLinkText')
    for city in search_cities:
        time.sleep(2)
        city.click()
        time.sleep(3)
        stores = driver.find_elements_by_class_name('Teaser-titleLink')
        time.sleep(2)

        # - click on the store
        for store in stores:
            store.click()
            time.sleep(5)

Any help would be much appreciated! Thank you

2
  • What you want to do is get the length of the items you want to loop and then index them while using driver.back on each store and then driver.back on the city. Commented Nov 16, 2020 at 5:41
  • can you show the code for one of the loops? Commented Nov 16, 2020 at 6:27

1 Answer 1

1

This should go to each store in a city.

stores = driver.find_elements_by_class_name('Teaser-titleLink')
for i in range(len(stores)):
    driver.find_elements_by_class_name('Teaser-titleLink')[i].click()
    driver.back()
driver.back()

You could also use xpath and use the index

Sign up to request clarification or add additional context in comments.

3 Comments

what is the difference between using for i in range and my method?
would you be able to show the whole code? I'm getting an index out of range error when trying to do it your way - thank you
When you leave a page you have to get the elements again or they will become stale.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.