通过 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();
}

有人告诉我编写脚本,我必须将变量传递到 xpath 以使其更健壮,但是作为变量传递给 xpath 的属性值不是定位元素,而是当我直接传递它时作为 xpath 中的一个属性值,它定位一个元素。而且,这是我收到的错误消息--

没有这样的元素:无法定位元素:{"method":"xpath","selector":"//span[normalize-space()='+mainMenu+']"

xpath里面变量的使用是错误的。请尝试以下操作:

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();

}