Я получаю значения из таблицы и, сравнивая, я получаю слова разделены полностью - PullRequest
0 голосов
/ 14 февраля 2019
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Testing\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("https://jpetstore.cfapps.io/catalog");
driver.findElement(By.xpath("//a[contains(text(),'Sign In')]")).click();
driver.findElement(By.name("username")).sendKeys("Testing6738788");
driver.findElement(By.name("password")).sendKeys("test@123");
driver.findElement(By.id("login")).click();
driver.findElement(By.xpath("//div[@id='SidebarContent']/a[contains(@href,'FISH')]/img")).click();
driver.findElement(By.xpath("//td[contains(text(),'Angelfish')]//preceding-sibling::td//a")).click();
List<WebElement> tablelist = driver.findElements(By.xpath("//div[@id='Catalog']//tr"));

for(int i = 0; i < tablelist.size(); i++)
{
    String gotvalues = tablelist.get(i).getText();
    System.out.println("Values got from the table  " +gotvalues);
    // Here im using split function but no luck
    String[] splitword = gotvalues.split(" ");
    for(String words : splitword)
    {
        System.out.println("Got single words from the split " + words);
        // I want to compare the Large Angelfish value from the output
        if(words.equalsIgnoreCase("Large Angelfish"))
        {
            System.out.println("Element present " + words);
        }
    }
}

Слова должны быть разделены как "Item ID" -EST-1.У меня проблема с описанием.Полное слово не отображается.Как написать код для получения идентификатора товара, идентификатора продукта и описания?

Ответы [ 2 ]

0 голосов
/ 14 февраля 2019

Поскольку вы хотите сравнить данные таблицы, вам нужно немного изменить ваш xPath, чтобы эффективно извлекать данные, чтобы вы могли избежать разделения и легко сравнивать данные.

Попробуйте приведенный ниже код:

String xPath = "//div[@id='Catalog']//tr";
List<WebElement> tableList = driver.findElements(By.xpath(xPath));
System.out.println("Item ID\t\tProduct ID\t\tDescription\t\tList Price\t\tOther");
System.out.println("--------------------------------------------------------------------------------------------------");
for(int i=1;i<tableList.size();i++) {
    // Below line fetches/stores each table data as column wise
    List<WebElement> listData = driver.findElements(By.xpath(xPath+"["+(i+1)+"]/td"));
    for(int j=0;j<listData.size();j++) {
        // Printing the column data
        System.out.print(listData.get(j).getText()+"\t\t");
    }
    System.out.println();
}

// As per the above output, description is in the 3rd(2nd index) column so you can fetch that with the index number 2.
for(int i=1;i<tableList.size();i++) {
    List<WebElement> listData = driver.findElements(By.xpath(xPath+"["+(i+1)+"]/td"));
    if(listData.get(2).getText().trim().equals("Large Angelfish")) {
        System.out.println("=> 'Large Angelfish' is Matching...");
    }

    if(listData.get(2).getText().trim().equals("Large Angelfish")) {
        System.out.println("=> 'Small Angelfish' is Matching...");
    }
}

Если вы выполните вышеуказанный код, он напечатает вывод, как показано ниже:

Item ID     Product ID      Description     List Price      Other
----------------------------------------------------------------------------
EST-1       FI-SW-01        Large Angelfish     $16.50      Add to Cart     
EST-2       FI-SW-01        Small Angelfish     $16.50      Add to Cart 

В вышеприведенном выводе номер столбца описания равен 3, так что вы можете заменить индексный номерв строке ниже для соответствующего столбца:

listData.get(2).getText().trim().equals("Large Angelfish")

Надеюсь, это поможет ...

0 голосов
/ 14 февраля 2019

Без String Array также вы можете проверить. Попробуйте этот код, чтобы увидеть, если это поможет. Возьмите ввод с клавиатуры. Вы должны ввести оба значения в консоли, как EST-1, затем Enter и Then Large Angelfish и их сравнение позже. Попробуйте сейчас.

 Scanner scan= new Scanner(System.in);
    String textID= scan.nextLine(); //Enter ID Here
    String textDesc= scan.nextLine();//Enter Desc Here
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\Testing\\Downloads\\chromedriver_win32\\chromedriver.exe");
            driver = new ChromeDriver();
            driver.navigate().to("https://jpetstore.cfapps.io/catalog");
            driver.findElement(By.xpath("//a[contains(text(),'Sign In')]")).click();
            driver.findElement(By.name("username")).sendKeys("Testing6738788");
            driver.findElement(By.name("password")).sendKeys("test@123");
            driver.findElement(By.id("login")).click();

        driver.findElement(By.xpath("//div[@id='SidebarContent']/a[contains(@href,'FISH')]/img")).click();
        driver.findElement(By.xpath("//td[contains(text(),'Angelfish')]//preceding-sibling::td//a")).click();
       List<WebElement> tablelist = driver.findElements(By.xpath("//div[@id='Catalog']//tr/td"));
       System.out.println(tablelist.size());

     for(int i=0;i<tablelist.size();i++)
    {
        String gotvalues = tablelist.get(0).getText();
        String gotvaluesdesc = tablelist.get(2).getText();

       // System.out.println("Values got from the table  " +gotvalues  );
        if(gotvalues.trim().equalsIgnoreCase(textID) && gotvaluesdesc.trim().equalsIgnoreCase(textDesc))

        {
            System.out.println("Element present ID: " + gotvalues + " Desc :" + gotvaluesdesc);
            break;
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...