在 selenium webdriver 中,验证所有产品是否按名称排序

问题描述 投票:0回答:6

在 Selenium WebDriver 中,如果我选择按“名称”下拉值,那么如何验证所有产品是否按名称排序?

这是我的代码:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class Magneto
{

    public static void main(String[] args) throws Exception {

        WebDriver d1 = new FirefoxDriver();
        d1.navigate().to("http://live.guru99.com/index.php/");
        d1.manage().window().maximize();
        if (d1.getTitle().equals("Home page")) {
            System.out.println("title matched");
        } else {
            System.out.println("title not matched expected title is "
                + d1.getTitle());
        }
        d1.findElement(By.xpath("//nav[@id='nav']/ol/li[1]/a")).click();
        Thread.sleep(2000);
        if (d1.getTitle().equals("Mobile")) {
            System.out.println("title matched");
        } else {
            System.out.println("title not matched expected title is "
                + d1.getTitle());
        }
        Select s1 = new Select(d1.findElement(By.xpath("//html[@id='top']/body/div[1]/div/div[2]/div/div[2]/div[1]/div[3]/div[1]/div[1]/div/select")));
        s1.selectByVisibleText("Name");}}
selenium webdriver
6个回答
1
投票

将以下代码添加到您的 main 方法中

//create an LinkedList instead of arraylist because it preserves insertion order

List<WebElement> products_Webelement = new LinkedList<WebElement>();

//store the products (web elements) into the linkedlist

products_Webelement = d1.findElements(By.xpath("//img[contains(@id, 'product-collection-image')]"));

//create another linked list of type string to store image title

LinkedList<String> product_names =  new LinkedList<String>();

//loop through all the elements of the product_webelement list get it title and store it into the product_names list

for(int i=0;i<products_Webelement.size();i++){

    String s = products_Webelement.get(i).getAttribute("alt");

    product_names.add(s);

}

//send the list to chkalphabetical_order method to check if the elements in the list are in alphabetical order    

boolean result = chkalphabetical_order(product_names);


//print the result    

System.out.println(result);

在chkalphabetical_order方法中,我们使用compareTo方法检查元素是否按字母顺序排列,因为java中的字符串类实现了Comparable,并且将使用字符串自然顺序进行比较。如果元素按字母顺序排列,该方法将返回true否则返回 false

    public static boolean chkalphabetical_order(LinkedList<String> product_names){

    String previous = ""; // empty string

    for (final String current: product_names) {
        if (current.compareTo(previous) < 0)
            return false;
        previous = current;
    }

    return true;

    }

希望这对您有帮助。我测试了上面的代码,它工作得很好。如果您有任何疑问,请回来


1
投票
String sortElement = driver.findElement(By.xpath("//li[1]//a[@class=\"product-image\"]")).getAttribute("title");
Assert.assertEquals(sortElement, "IPhone");
sortElement = driver.findElement(By.xpath("//li[2]//a[@class=\"product-image\"]")).getAttribute("title");
Assert.assertEquals(sortElement, "Samsung Galaxy");
sortElement = driver.findElement(By.xpath("//li[3]//a[@class=\"product-image\"]")).getAttribute("title");
Assert.assertEquals(sortElement, "Xperia");

0
投票

我有一个场景,我必须验证排序的菜单

try{
        List<WebElement> lst = driver.findElements(By
                .xpath(".//*[@id='global-wrapper']/nav/ul/li"));
        String[] str = new String[lst.size()];
        String[] ORGstr = new String[lst.size()];

    int i = 0;
    int l = 0;
    for (WebElement ele1 : lst) {
        if (ele1.getText() != null)
            ORGstr[l] = ele1.getText();
        l++;
    }

    for (WebElement ele : lst) {
        if (ele.getText() != null)
            str[i] = ele.getText();
        i++;
    }

    for (int b = 0; b < str.length; b++) {

        for (int j = b + 1; j < str.length; j++) {
            if (str[b].compareTo(str[j]) > 0) {
                String temp = str[b];
                str[b] = str[j];
                str[j] = temp;
            }

        }
    }
    int o = 1;
    int s = 0;

    for (int k = 0; k < str.length; k++) {
        //System.out.println("Sorted Order " + str[s] + " ");
        //System.out.println("Original Order " + ORGstr[o] + " ");
        if (!(str[s].equalsIgnoreCase("Dashboard"))) {
            if (str[s].equalsIgnoreCase(ORGstr[o])) {
                assertEquals(str[s], ORGstr[o]);
                o++;
                log.debug("verified dashboard menu is sorted");
            } else {

                Assert.fail();
            }
        }
        s++;

    }

    }catch(Exception e){

        ErrorLog.fatal("Error: Element not located in menu");   
    }

在我的代码中,我必须跳过一个名为仪表板的菜单项,我根据我的要求编写了它,您可以相应地更改!!!!


0
投票
List<WebElement> li=new LinkedList<>(obj.findElements(By.xpath("//h2[@class='product-name']/a")));    
        LinkedList<String> pn=new LinkedList<String>();    
        for(int i=0;i<li.size();i++)    
        {    
             //just displaying the product names    
            //System.out.println(li.get(i).getText());    
            pn.add(li.get(i).getText());    
        }    
        boolean result = comp_order(pn);    

you need to add one more method    

//alphabetical order checking    
    public static boolean comp_order(LinkedList<String> pn)    
    {           
        String prev=""; // empty string    
        for (final String cur: pn)    
        {    
            if (cur.compareTo(prev) < 0)    
            {      
                return false;     
            }    
            prev=cur;    
        }    
        return true;    
        }    

i did nothing just improved previous solution its working    

0
投票

如果产品名称同时以小写字母和大写字母开头,则此排序方法将失败。

如果你跑步,并检查

public class Testing
{
    public static void main(String[] args)
    {
        String name1= "pro";
        String name2= "TestPro";
        int tmp=name2.compareTo(name1);
        System.out.println(tmp);
    }
} 
Output: -28

尽管如此,我们期望它返回一些正整数。

所以,为了摆脱这个问题,我们需要将所有名称转换为小写,然后检查它们是否已排序?

这是我的做法,我的代码还有一些其他功能,您可以忽略。

public class SortingTest 
{
    static WebDriver driver;

    @Test
    public static void AnchorTags() throws InterruptedException
    {

        driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        Thread.sleep(5000);
        driver.get("http://xyz21314131.co");

        driver.findElement(By.linkText("Ascending Order")).click();
        Thread.sleep(5000);
        WebElement Row=driver.findElement(By.xpath("//* [@id='content']/div/div[2]"));
        List<WebElement> Anchortags=Row.findElements(By.tagName("a"));

        //Linked List to Store ProductNames
        LinkedList<String> productNames=new LinkedList<String>();

        int size=Anchortags.size();

        for(WebElement temp:Anchortags)
        {
            String sTemp=temp.getText();
          //Important
           **// to remove extra spaces and to Lowercase Every product name**
            productNames.add(sTemp.toLowerCase().trim());           
        }
        System.out.println(productNames);


        //Check SortedOr NOt?

        Boolean num=checkDescendingOrder(productNames);
        System.out.println("boolean value"+ num);
        if(num==true)
        {

            System.out.println("Products names are Sorted in ascending Order");
        }
        else {
            System.out.println("Products names are not Sorted in ascending Order");
            }
        System.out.println("New List:--"+productNames);
        System.out.println("Size is " + size);
    }

public static boolean checkAscendingOrder(LinkedList<String> Names)
{
    String previous = ""; // empty string

    for (String current: Names) {
        if (current.compareTo(previous) < 0)
        {
            return false;
        }
        previous = current;
    }
    return true;
    }   
}

0
投票

这对我有用,非常感谢。 问候, 文卡特拉姆

© www.soinside.com 2019 - 2024. All rights reserved.