NegativeFriction
NegativeFriction

Reputation: 576

Using selenium find_elements_by_xpath is returning an array of the same element multiple times rather than all elements

I'm trying to write a bot to reserve a specific time for a specific activity on a gym website. The gym's website looks like this:

Gym Website

with multiple instances of various activities like "Basketball Room," "Gym Main Access," "Swimming Pool," and other activities. My goal is to select every "block" of information and store it in an array. Then, I can iterate through the array and separate out activities by availability, type, and time.

My code looks like this:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC

listOfClasses = browser.find_elements_by_xpath("//div[@ng-repeat='class in value']")
for classBlock in listOfClasses:
    n = classBlock.find_element_by_xpath("//h1[@class='class-title ng-binding']")
    t = classBlock.find_element_by_xpath("//div[@class='row class-details']/div[@class='col-lg-3 ng-binding'][2]")
    print("Class:",n.text,"Time of class",t.text)

There are 142 possible classes to choose from on the page. When I run my script, listOfClasses is 142 items long, but when I inspect the values of n (the name of the class) and t (the time of the class), indexes 0-3 have no value, and indexes 4-141 are all just value of the first element on the page. I only have instances of the Basketball Room from 5:00 AM to 6:00 AM.

It would seem that either my initial array of classes is being occupied only by the first element on the page, or else that I'm searching through the same item in listOfClasses each time. What am I doing incorrectly?

Upvotes: 2

Views: 782

Answers (1)

NegativeFriction
NegativeFriction

Reputation: 576

So turns out, I'm not the first person to make this error. I found this useful related question that I'm inadvertently duplicating. Essentially the "//" option tells selenium to begin searching from the root of the document. Instead, I want ".//" which tells it to search only through child nodes of the current node in its results.

Upvotes: 2

Related Questions