首页 > 解决方案 > 用 selenium 和 Python 读出 div 中的类名

问题描述

网站检查员截图

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

(我确实取回了类名“lcs black ui-droppable”,但我确实想取回了类名“lichess piece knight white ui-draggable”)

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

这是我的代码:

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

print(name)

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

谢谢你的提示!

标签: pythonseleniumclassname

解决方案


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

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


推荐阅读