Search code examples
pythonseleniumclassname

Read out the name of a class inside a div with selenium and Python


Screenshot of Website Inspector

As you can see in the picture, I would like to inspect a chessboard. I use Python and Selenium for this. My wish is to have a function that I can pass the names of the chess fields one after the other, e.g. g1, g2, g3 ... There are objects on the website whose ID matches these names. Now I would like to get back the name of the figure that is on the field. The name is in the class name of the object. However, within a div.

(I do get back the classname 'lcs black ui-droppable' but I do want to get back the classname 'lichess piece knight white ui-draggable')

My question is how can I extract this class name.

Here is my code:

def getFigure(position):
figure = driver.find_element_by_id(position)
name = figure.get_attribute("class")

print(name)

I do pass the name of the field into the position variable.

Thank you for your tips!


Solution

  • print(figure.find_element_by_xpath("./div[2]").get_attribute("class"))
    

    You can xpath from the parent element and get the 2nd div.