如何从WebElement获取xpath

时间:2018-05-29 07:35:03

标签: selenium xpath

如何从WebElement获取xpath

Webelement element= driver.findElement(By.xpath("//div//input[@name='q']"));

类似

element.getLocator(); ->> this should be like this "//div//input[@name='q']"

如何做同样的事情? 我创建了下面的方法并将xpath作为参数传递。我想创建相同的方法并将webElement作为参数传递:

public boolean isElementPresentAndVisible(String xpath){
    if(driver.findElements(By.xpath(xpath)).size()!=0){
        if(driver.findElement(By.xpath(xpath)).isDisplayed()){
            System.out.println(xpath+" present and Visible");
            return true;
        }else{
            System.err.println(xpath+" present but NOT Visible");
            return false;
        } 
    }else{
        System.err.println(xpath+" NOT present");
        return false;
    } 

}

2 个答案:

答案 0 :(得分:1)

通过id或name获取WebElement,然后调用方法generate generateXPATH()传递元素。它将返回Xpath.Find代码:

 String z=generateXPATH(webElement, "");//calling method,passing the element

 public static String generateXPATH(WebElement childElement, String current) {
        String childTag = childElement.getTagName();
        if(childTag.equals("html")) {
            return "/html[1]"+current;
        }
        WebElement parentElement = childElement.findElement(By.xpath("..")); 
        List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
        int count = 0;
        for(int i=0;i<childrenElements.size(); i++) {
            WebElement childrenElement = childrenElements.get(i);
            String childrenElementTag = childrenElement.getTagName();
            if(childTag.equals(childrenElementTag)) {
                count++;
            }
            if(childElement.equals(childrenElement)) {
                return generateXPATH(parentElement, "/" + childTag + "[" + count + "]"+current);
            }
        }
        return null;
    }

答案 1 :(得分:0)

没有方法可以做你要求的但你无论如何也不需要它。你使它变得比它需要的更复杂。如果元素可见,它也会出现,因此无需检查是否存在。

而不是传递XPath作为字符串,而是传递By定位器。现在您可以使用任何所需的定位器类型。我已经重写并简化了您的代码,然后编写了带有WebElement参数的类似函数。

public boolean isVisible(By locator)
{
    List<WebElement> e = driver.findElements(locator);
    if (e.size() != 0)
    {
        return isVisible(e.get(0));
    }

    return false;
}

public boolean isVisible(WebElement e)
{
    try
    {
        return e.isDisplayed();
    }
    catch (Exception)
    {
        return false;
    }
}