Home > Enterprise >  Selenium find class with index
Selenium find class with index

Time:06-20

Hey all trust that you're well, I'm trying to find elements by class_name and loop through them, however, they all have the same class_name.

I've discovered that they contain different index numbers and I'm trying to utilise that to loop through them

Example of the element and the index:

<div  aria-controls="popout_4188" aria-expanded="false" tabindex="-1" colorroleid="987314373729067059" index="0" role="listitem" data-list-item-id="members-987320208253394947___0">
<div  aria-controls="popout_4184" aria-expanded="false" tabindex="-1" colorroleid="987324577870929940" index="1" role="listitem" data-list-item-id="members-987320208253394947___1">

My code:

    users = bot.find_elements(By.CLASS_NAME, 'member-2gU6Ar')
        
    time.sleep(5)

    try:
        for user in users:
            user.click()
            message = bot.find_element(By.XPATH, '//body[1]/div[1]/div[2]/div[1]/div[3]/div[1]/div[1]/div[1]/div[5]/div[1]/input[1]')
            time.sleep(5)
            message.send_keys('Automated'   Keys.ENTER)
    except NoSuchElementException:
        skip

first user in the list to the left of the inspect page

second user in the list to the left of the inspect page

CodePudding user response:

The class that you see over here member-2gU6Ar container-1oeRFJ clickable-28SzVr is not a single class, it is a combination of multiple classes separated with space.

So using member-2gU6Ar would not work as expected.

You can remove the spaces and put a . to make a CSS selector though.

div.member-2gU6Ar.container-1oeRFJ.clickable-28SzVr

I would not really suggest that since I see it contains alpha numeric string, that may get change with the time.

Here I have written an xpath:

//div[starts-with(@class,'member') and contains(@class, 'container') and @index]

this should match all the divs with the specified attribute.

You can use it probably like this:

users = bot.find_elements(By.XPATH, "//div[starts-with(@class,'member') and contains(@class, 'container') and @index]")
i = 1
time.sleep(5)
try:
    for user in users:
        ele = bot.find_element(By.XPATH, f"//div[starts-with(@class,'member') and contains(@class, 'container') and @index= '{i}']")
        ele.click()
        message = bot.find_element(By.XPATH, '//body[1]/div[1]/div[2]/div[1]/div[3]/div[1]/div[1]/div[1]/div[5]/div[1]/input[1]')
        time.sleep(5)
        message.send_keys('Automated'   Keys.ENTER)
        i = i   1
except NoSuchElementException:
    skip

However I would recommend you to use a relative xpath and not absolute xpath //body[1]/div[1]/div[2]/div[1]/div[3]/div[1]/div[1]/div[1]/div[5]/div[1]/input[1].

Hope this helps.

  • Related