用 selenium 和 Python 读出 div 中的类名

问题描述

Screenshot of Website Inspector

正如你在图片中看到的,我想检查一个棋盘。为此,我使用 Python 和 Selenium。我的愿望是有一个函数,我可以一个一个地传递国际象棋领域的名称,例如g1,g2,g3 ... 网站上存在 ID 与这些名称匹配的对象。现在我想取回在场上的人物的名字。名称在对象的类名中。但是,在一个 div 内。

(我确实找回了类名“lcs black ui-droppable”,但我确实想找回了类名“lichesspiece Knight white ui-draggable”)

我的问题是如何提取这个类名。

这是我的代码

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

print(name)

我确实将字段的名称传递给位置变量。

感谢您的提示

解决方法

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

您可以从父元素 xpath 并获得第二个 div。