获取span web元素的Xpath

问题描述 投票:0回答:3

我有以下HTML代码:

enter image description here

我需要引用span元素(树中的最后一个元素)以检查它是否存在。问题是,我找不到合适的XPath,并且无法找到任何有关此特定问题的问题。

我试过了:

"//span[@data-highlighted='true']"

还有更多的连续XPath引用它以前的节点,但实际上无法获得有效的Xpath。对我来说困难在于它没有id或title,所以我试图通过它的“数据突出显示”,但这似乎不起作用。

仅仅为了完整起见:我编写了以下Java方法,该方法用于获取Xpath作为输入:

public Boolean webelementIsPresent (String inputXpath) throws InterruptedException {
return driver.findElements(By.xpath(inputXpath)).size()>0;
}

然后在测试类中,我执行一个assertTrue,webelement存在(该方法返回一个True)或者它没有。

我愿意提供任何帮助,谢谢! :)

java html selenium xpath selenium-webdriver
3个回答
1
投票

你可以逐个文本地获取

driver.findElement(By.xpath("//span[contains(text(), 'Willkommen')]"));

或者找到divid并在此基础上找到span元素。有两种选择:

driver.findElement(By.xpath("//div[@id='description']//span"));

要么

WebElement descriptionDiv = driver.findElement(By.id("description"));
descriptionDiv.findElement(By.tagName("span"));

要么

driver.findElement(By.cssSelector("#description span"));

0
投票

要识别元素"//span[@data-highlighted='true']",您可以使用以下xpath

"//table[@class='GJBYOXIDAQ']/tbody//tr/td/div[@class='GJBYOXIDPL' and @id='descriptionZoom']/table/tbody/tr/td/div[@class='GJBYOXIDIN zoomable highlight' and @id='description']/div[@class='gwt-HTML' and @id='description']//span[@data-highlighted='true']"

-1
投票

你的XPath看起来很好,我的猜测是这是一个时间问题,你需要一个简短的等待。也可能是当您捕获HTML时页面处于某种状态,并且当您到达页面时它并不总是处于该状态。

还有其他定位器应该在这里工作。

XPath的

//span[contains(., 'Willkommen')]

CSS选择器(这些可能会或可能不会根据您当前的XPath结果工作)

span[data-highlighted='true']
#description span[data-highlighted='true']

对于你的功能,我建议改变。用String替换By参数以获得更大的灵活性。然后,您可以使用任何方法定位元素,而不仅限于XPath。

public Boolean webElementIsPresent(By locator)
{
    return driver.findElements(locator).size() > 0;
}

或者如果你想添加一个等待,

public Boolean webElementIsPresent(By locator)
{
    try
    {
        new WebDriverWait(driver, 5).until(ExpectedConditions.presenceOfElementLocated(locator));
        return true;
    }
    catch (TimeoutException e)
    {
        return false;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.