如何在tr td中的表中找到元素

时间:2020-04-01 18:36:38

标签: java html selenium

HTML代码如下:

<div id = ...>
  <table ...>
    <tbody>
      <tr>
        <td>
          <table ...>
            <tr>
              <td>
                <a onclick="…" class="xl" href="#">1111111</a>

我需要找到最后一个值为111111的单元格/元素,然后单击它。

我尝试了这些Java:

driver.findElement(By.xpath("//tr/td/a[contains(text(),'111111')]")).click();
driver.findElement(By.cssSelector("a[href='#']")).click();

但是没有用。

有什么主意吗?谢谢

3 个答案:

答案 0 :(得分:1)

如果您想要最后一个具有111111值/文本的元素,那么我将使用findElements,然后单击最后一个:

List<WebElement> listOfElements = driver.findElements(By.xpath("//*[text()='111111']"));

int lastElementIndex = listOfElements.size() - 1;

listOfElements[lastElementIndex].click();

答案 1 :(得分:1)

为什么不收集表主体中所有行的文本。

WebElement container = Webdriver.findElement(By.xpath("/*xpath to <tbody> element here*/")).click();
List<WebElement> tableRows = container.findElement(By.tagName("tr"));
List<String> elementText = new ArrayList<>();
tableRows.foreach(x -> elementText.add(x.getText()));

然后搜索该字符串的最后一个索引

int indexOfLast = tableRows.lastIndexOf("1111111");
WebElement theLastElement = elementText.get(indexOfLast);

然后,您可以获取最后一个元素,并使用它来查找要查找的带标签的元素。

WebElement myElement = theLastElement.findBy(tagName("a"));

答案 2 :(得分:1)

请尝试以下代码:

//Storing the value from the table we have to click 
String tablevalue = "111111";

//Get all the WebElements from second line having values
//***We might have to update the xpath***
List<WebElement> allTableValues = driver.findElements(By.Xpath("//tr/td//a"));

//Clicking on Element which matches our Value from all Table Values
for(WebElement ele: allTableValues){
    if(ele.getText().equals(tablevalue)){
    ele.click();
    break;
    }
}

您也可以更改tableValue变量的值,以使用相同的代码单击其他表值。

相关问题