0

I have a table that contains multiple rows and columns.

I need to locate an element in column one that lies in the same row with a particular element in colum two.

Here is apart of HTML

<tr>
<td element1>
</td>
<td element2>
</td>
</tr>

<tr>
<td element3>
</td>
<td element4>
</td>
</tr>

Elements: element1 and element3 have absolutely the same HTML. The only thing that I can use to differentiate between them is their sibling elements: element3 and element4.

I need to locate element3 BECAUSE it is a sibling of element 4. So first I need to narrow down my search to element that are in the same row <tr as element4. Then, I can locate element3. How can I do this?

PS: I cannot use .get(2) or tr[2] ... etc. But I can navigate element2 and element 4 individually

4

2 回答 2

5

在 Selenium 2 中,您可以使用以下 CSS 选择器进行选择

driver.findElement(By.cssSelector("table tr:nth-child(X) > td:nth-child(X)"));
于 2013-10-17T14:48:06.357 回答
1

The following pieces of code should work:

List<WebElement> elements = driver.findElements(By.cssSelector("table tr > td"));
for (int i = 0; i < elements.size; i++){
    if (elements[i].getAttribute("attribute that will identify element 4").equals("something")){
       elements[i-1].performAction();
}

Alternatively, the better way is to use an XPath selector. I generally don't like XPath, but this is a case where I would use it.

Because I don't know the special selector to get the element, here's how "previous sibling works" on XPath:

//E/preceding-sibling::*[1]

Where E is the selector to get to the element.

于 2013-10-17T15:28:21.610 回答