是的,这绝对是可能的。看看这个:
// Find the outer element.
WebElement outer = driver.findElement(By.anything("whatever"));
// This doesn't work, it searches the whole page for the XPath expression.
WebElement inner = outer.findElement(By.xpath("//some/nasty/xpath"));
// This works! It takes the outer element as root.
WebElement inner = outer.findElement(By.xpath(".//some/nasty/xpath"));
因此,如果我很好地理解了您的需求,您的 XPath 表达式需要如下所示:
By.xpath("(.//tbody)[" + j + "]//div[text()=\"" + collector + "\"])")
EDIT(天哪,这是很多 HTML,但实际上只需要一小部分:)。)
现在我明白了您的需求,我认为您根本不需要这种方法。试试这个:
WebElement row = driver.findElement(By.xpath("id('CollectorQoSPerformanceMetricsgrid')//div[contains(@class,'x-grid3-row x-unselectable-single') and .//u[text()='" + collector + "']]"));
仅 XPath 表达式:
id('CollectorQoSPerformanceMetricsgrid')
//div[contains(@class,'x-grid3-row x-unselectable-single')
and .//u[text()='" + collector + "'] ]
拆开来看:
FIND ELEM WITH ID = 'CollectorQoSPerformanceMetricsgrid'
id('CollectorQoSPerformanceMetricsgrid')
FIND ALL DIV ELEMS THAT CONTAIN 'x-grid3-row x-unselectable-single' IN @CLASS
//div[contains(@class,'x-grid3-row x-unselectable-single')
AND HAVE AN <U> DESCENDANT WITH TEXT EQUAL TO collector VARIABLE
and .//u[text()='" + collector + "'] ]
这将通过单个命令仅找到您需要的单行。
如果您想坚持使用当前的解决方案,请尝试:
String rowsXpath = "id('CollectorQoSPerformanceMetricsgrid')//div[contains(@class, 'x-grid3-row x-unselectable-single')]";
List<WebElement> rows = driver.findElements(By.xpath(rowsXpath));
boolean foundCollector = false;
for(WebElement row : rows) {
if(!row.findElements(By.xpath(".//u[text()='" + collector + "']")).isEmpty()) {
foundCollector = true;
break;
}
}