selenium 如何从WebElement获取xpath

k5ifujac  于 2023-01-13  发布在  其他
关注(0)|答案(3)|浏览(564)

如何从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;
    } 

}
u0njafvf

u0njafvf1#

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

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;
    }
iecba09b

iecba09b2#

没有方法来完成你所要求的,但是你也不需要它。你把它弄得比实际需要的更复杂。如果一个元素是可见的,它也是存在的,所以没有必要检查它是否存在。
不是将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;
    }
}
iaqfqrcu

iaqfqrcu3#

@shamsher Khan的答案的Python版本--它工作。

def gen_xpath(child: WebElement, curr: str=''):
    if (child.tag_name == 'html'): return f'/html[1]{curr}'

    parent = child.find_element(By.XPATH, '..')
    children = parent.find_elements(By.XPATH, '*')
    i = 0
    for c in children:
        if c.tag_name == child.tag_name: i += 1
        if c == child: return gen_xpath(parent, f'/{child.tag_name}[{i}]{curr}')

相关问题