如何使用 Selenium 查找 CSS 个元素的 ID、名称、类

How to find IDs, Names, Classes of CSS Elements with Selenium

我正在努力解决这个问题,我真的想不通,我应该在哪里寻找特定元素的标识。在网上找到的很多例子中,大多数元素都有明确的ID、名称等。 我正在测试的网页包含没有 ID 或名称的元素。他们大部分时间只有“类型”、“class”等。 我知道,我可以使用“class”作为标识,但在今天与同事交谈后,他建议我不要在查找元素中使用 class,因为它们是 CSS class在网页上出现不止一次的es。

这是我想从中获取标识的搜索字段检查示例。

<input type="text" class="mud-input-slot mud-input-root mud-input-root-text mud-input-root-adorned-start" placeholder="Search here" _bl_7285135c-aa68-4a79-981f-4ee1af405a95="">

我现在用这个,确实有效。

webDriver.FindElement(By.XPath("//input[@placeholder='Search here']")).SendKeys("Super");

但在其他元素中,我在 XPath 中使用“class”,我想更改它。这样的例子在这里: 检查文本字段:

<input type="text" class="mud-input-slot mud-input-root mud-input-root-text mud-input-root-margin-normal" placeholder="Name" _bl_b3249641-8126-4e48-a3fd-9fd64aa2fb80="">

目前正在查找元素:

IWebElement TitleField = webDriver.FindElement(By.XPath("//input[@class='mud-input-slot mud-input-root mud-input-root-text mud-input-root-margin-normal']"));

我的同事也提到,我可以在 spectace 中右键单击一个元素,单击复制并选择“复制选择器”或“复制 XPath”。

但是当我点击“复制 XPath”时,我会得到这个:

/html/body/div[2]/div/div/div/div[1]/div[2]/div/div/input

或者选择器是这样的:

body > div.mud-layout > div > div > div > div.mud-toolbar.mud-toolbar-gutters.mud-table-toolbar > div.mud-input-control.mud-input-input-control.mt-0 > div > div > input

这是我也可以在 FindElement 中使用的东西吗?

在我的示例中标识元素的其他可能方法有哪些?

你应该试试这个

IWebElement menu = CurrentDriver.FindElement(By.CssSelector("div[class='menu-panel right']"));

在大多数情况下,使用开发工具自动生成的定位器是无用的。
您必须学习如何创建正确、准确、强大和高效的定位器。
我们主要使用 CSS 选择器或 XPath 定位 Web 元素。
在大多数情况下,您将不得不同时使用元素标签和一些或几个元素属性来获得唯一的定位器。
很多时候,您必须指明一些独特的父元素属性才能到达该元素。
所以通常情况下,在现实生活中,元素定位器看起来像

//div[contains(@class,'ApplicationsView')]

//li[contains(@class,someClass')]//div[contains(@class,'thisClassName')]

甚至像这样

//div[contains(@class,'ObjectList')]//div[contains(@class,'ListItem')]/span/..//i[contains(@class,'active')]

你的第一个问题:

这是我也可以在 FindElement 中使用的东西吗? - 是的,你可以。但这将是一个可怕的 xpath,因为它是一个 absolute xpath。告诉您的同事我们应该始终使用 relative xpath.

Read here what is the difference between Absolute xpath and Relative xpath

你的下一个问题:

在我的示例中标识元素的其他可能方法有哪些? - 我会选择 css 选择器 .

为此 HTML :

<input type="text" class="mud-input-slot mud-input-root mud-input-root-text mud-input-root-margin-normal" placeholder="Name" _bl_b3249641-8126-4e48-a3fd-9fd64aa2fb80="">

只需将css selector写成:

input[placeholder='Name']

在您的 C# 中,它将是这样的:

IWebElement NameField = webDriver.FindElement(By.CssSelector("input[placeholder='Name']"));
NameField.SendKeys("Your name");