简体   繁体   English

通过 xpath 传递的字符串变量未定位元素并引发异常

[英]The string variable passed through an xpath is not locating the element and throwing an exception

public static void selectNavigationLink(String mainMenu, String subMenu) {

    WebElement mm = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[normalize-space()='+mainMenu+']")));
    mm.click();

    WebElement sm = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'+subMenu+')]")));
    sm.click();
}

I was told to write the script where I have to pass the variable into the xpath to make it more robust but the attribute value that is passed as variable to the xpath is not locating an element but when I pass it directly as an attribute value inside the xpath, it locates an element.有人告诉我编写脚本,我必须将变量传递给 xpath 以使其更健壮,但作为变量传递给 xpath 的属性值不是定位元素,而是当我直接将其作为内部属性值传递时xpath,它定位一个元素。 And, this is the error message I am getting--而且,这是我收到的错误消息-

no such element: Unable to locate element: {"method":"xpath","selector":"//span[normalize-space()='+mainMenu+']"没有这样的元素:无法找到元素:{"method":"xpath","selector":"//span[normalize-space()='+mainMenu+']"

The use of the variable inside xpath is wrong. xpath里面的变量使用是错误的。 Please try following:请尝试以下操作:

public static void selectNavigationLink(String mainMenu, String subMenu) {

WebElement mm = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[normalize-space()='" + mainMenu + "']")));
mm.click();

WebElement sm = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'" + subMenu + "')]")));
sm.click();

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM