Selenium 提取通过 Java 中的文本找到的元素的 ID
Selenium Extract the ID of an element found via text in Java
我有一组希望使用 selenium 和 Chrome 执行的 Cucumber 测试。我的大部分测试工作正常。我目前正在尝试对一个特定步骤进行参数化,以便任何使用测试的人都可以简单地命名他们想要的元素,测试就会找到它们。
Cucumber 测试看起来像这样:
When I go to the "Inventory" / "Inventory" application
And I search the "Description" field for "a"
我能够很容易地使 when 语句参数化,但是 And 语句给我带来了更多麻烦。该页面本身有几组具有一致 id 方案的表 header 的 xpath 与单词 "Description" 看起来像这样:
//label[@id='m6a7dfd2f_ttrow_[C:2]_ttitle-lb']
并且输入字段有这个 xpath
//td[@id='m6a7dfd2f_tfrow_[C:2]-c']/input
作为参考,位于标签房间下方的紧邻的下一个输入字段具有此 xpath
//td[@id='m6a7dfd2f_tfrow_[C:3]-c']/input
所以每个标签和输入字段都有相同的 ID 方案,只有 "c:" 后面的数字似乎会改变。该数字对于标签及其对应的输入值都是相同的。我想知道如何扫描页面中的单词 "Description" 并提取与其关联的元素的 ID,然后将其截断为数字。我已经设置了变量来保存其余部分,希望如下所示:
@When("^I search the \"([^\"]*)\" field for \"([^\"]*)\"$")
public void i_search_the_field_for(String searchField, String searchItem) throws Throwable {
String baseinputXPath = "//td[@id='m6a7dfd2f_tfrow_[c:";
String endinputXPath = "]-c']/input";
String elementNumber = "The return of some sort of method based on searchField";//TODO
driver.findElement(By.xpath(baseinputXPath + elementNumber + endinputXPath)).clear();
driver.findElement(By.xpath(baseinputXPath + elementNumber + endinputXPath)).sendKeys(searchItem);
driver.findElement(By.id("search_button_img")).click();
如果有一种方法可以仅根据描述文本提取该数字,那将非常有帮助。
使用 xpath 在 label 标记中搜索带有单词 'Description' 的 WebElement。
"//label[text(),'Description']" or "//label[.='Description']" or "//label[contains(text(),'Description')]"
使用getAttribute("id")
获取id。
我有一组希望使用 selenium 和 Chrome 执行的 Cucumber 测试。我的大部分测试工作正常。我目前正在尝试对一个特定步骤进行参数化,以便任何使用测试的人都可以简单地命名他们想要的元素,测试就会找到它们。
Cucumber 测试看起来像这样:
When I go to the "Inventory" / "Inventory" application
And I search the "Description" field for "a"
我能够很容易地使 when 语句参数化,但是 And 语句给我带来了更多麻烦。该页面本身有几组具有一致 id 方案的表 header 的 xpath 与单词 "Description" 看起来像这样:
//label[@id='m6a7dfd2f_ttrow_[C:2]_ttitle-lb']
并且输入字段有这个 xpath
//td[@id='m6a7dfd2f_tfrow_[C:2]-c']/input
作为参考,位于标签房间下方的紧邻的下一个输入字段具有此 xpath
//td[@id='m6a7dfd2f_tfrow_[C:3]-c']/input
所以每个标签和输入字段都有相同的 ID 方案,只有 "c:" 后面的数字似乎会改变。该数字对于标签及其对应的输入值都是相同的。我想知道如何扫描页面中的单词 "Description" 并提取与其关联的元素的 ID,然后将其截断为数字。我已经设置了变量来保存其余部分,希望如下所示:
@When("^I search the \"([^\"]*)\" field for \"([^\"]*)\"$")
public void i_search_the_field_for(String searchField, String searchItem) throws Throwable {
String baseinputXPath = "//td[@id='m6a7dfd2f_tfrow_[c:";
String endinputXPath = "]-c']/input";
String elementNumber = "The return of some sort of method based on searchField";//TODO
driver.findElement(By.xpath(baseinputXPath + elementNumber + endinputXPath)).clear();
driver.findElement(By.xpath(baseinputXPath + elementNumber + endinputXPath)).sendKeys(searchItem);
driver.findElement(By.id("search_button_img")).click();
如果有一种方法可以仅根据描述文本提取该数字,那将非常有帮助。
使用 xpath 在 label 标记中搜索带有单词 'Description' 的 WebElement。
"//label[text(),'Description']" or "//label[.='Description']" or "//label[contains(text(),'Description')]"
使用getAttribute("id")
获取id。