pandashugger
pandashugger

Reputation: 39

Using For Loop in Selenium - Web Testing

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

Upvotes: 0

Views: 67

Answers (1)

Arundeep Chohan
Arundeep Chohan

Reputation: 9969

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

Upvotes: 1

Related Questions