Как напечатать ссылки подменю без каких-либо атрибутов в Selenium - PullRequest
0 голосов
/ 06 июля 2018

Я новичок в селене и пытаюсь напечатать текст ссылок, используя LIST.

Я пытаюсь получить текст с одного демонстрационного сайта, но в локаторе нет ни одного атрибута. Поэтому, пожалуйста, помогите мне. Ниже приведены детали, которые я выполняю.

URL сайта: https://www.nopcommerce.com/

Меню: Продукт> Все подменю в Продукте (всего найдено 9 ссылок), но невозможно распечатать текст этих 9 ссылок.

Скриншот 1: введите описание изображения здесь

Снимок экрана 2: введите описание изображения здесь

Код, который я сделал:

 public void OpenStoreDemo() {
    List<WebElement> MainMenu = driver.findElements(By.xpath("//ul[@class='top-menu']/li[1]//a"));
    System.out.println(MainMenu.size());

    for (WebElement list : MainMenu) {

        String getname = list.getText();
        System.out.println(getname);

        if (getname.equals("Store demo")) {

            System.out.println("Pass");

        }
        else {
            System.out.println("Not Found");
        }
        break;
    }

}

Ответы [ 3 ]

0 голосов
/ 06 июля 2018

Следующий код может вам помочь.

public void OpenStoreDemo() {
    boolean isFound = false;
    WebElement MainMenuProduct = driver.findElement(By.xpath("//ul[@class='top-menu']/li[1]/a"));

    new Actions(driver).moveToElement(MainMenuProduct).perform();

    List<WebElement> lstProductSubmenu =driver.findElements(By.xpath("//ul[@class='top-menu']/li[1]//ul/li/a"));

    for (WebElement list : lstProductSubmenu) {

        String getname = list.getText();
        System.out.println(getname);

        if (getname.equals("Store demo")) {

            System.out.println("Pass");
            isFound = true;
            break;
        }


    }
    if(!isFound)
       System.out.println("not found");

}
0 голосов
/ 06 июля 2018

Вы можете использовать JS метод для получения текста из скрытого веб-элемента и поставщик данных для проверки, включен ли пункт меню, это может быть так:

 @DataProvider
public Object[][] getProductMenu() {
    return new Object[][]{
            {"What is nopCommerce"},
            {"Why nopCommerce"},
            {"Features"},
            {"Store demo"},
            {"Showcase"},
            {"Case studies"},
            {"Roadmap"},
            {"Copyright notice removal"},
            {"License"}
    };
}

@Test(dataProvider = "getProductMenu")
public void checkProductMenu(String menuItemName) {
    driver.get("https://www.nopcommerce.com/");
    // check if menu item is enabled
    Assert.assertTrue(isMenuItemExistInMenu(menuItemName));
}

public boolean isMenuItemExistInMenu(String menuItemName) {
    List<WebElement> menuItemsElements = driver.findElements(By.xpath("//ul[@class='top-menu']/li[1]//ul/li/a"));
    for (WebElement menuItemsElement : menuItemsElements) {
        if (getHiddenTextByWebElement(menuItemsElement).equals(menuItemName)) {
            System.out.println("Menu item [" + menuItemName + "]" + " is enabled in Product submenu");
            return true;
        }
    }
    return false;
}

//this is JS method for get hidden text from WebElement
private String getHiddenTextByWebElement(WebElement element) {
    try {
        return (String) driver.executeScript("return arguments[0].innerHTML", element);
    } catch (Exception e) {
        Assert.fail("Can't return hidden text, occur error: \n" + e.getMessage());
        return "";
    }
}
0 голосов
/ 06 июля 2018

Попробуйте это:

// to make 'Store demo' button visible, hover to 'product' button
Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.xpath("//ul[@class = 'top-menu']/li[1]/a")));
actions.perform();

// wait until 'Store demo' button will be clickable
new WebDriverWait(webDriver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//ul[@class = 'top-menu']/li[1]/ul/li[4]/a")));
// locate element
WebElement storeDemoBtn = driver.findElement(By.xpath("//ul[@class = 'top-menu']/li[1]/ul/li[4]/a"));
System.out.println(storeDemoBtn.getText()); // will print 'Store demo'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...