简体   繁体   中英

How to Create variable for an element in a webpage using webdriver

i'm using webdriver to find element in a webpage. The webpage contains different elements.

So to find an element i use this code:

try {
              driver.findElement(By.linkText("Item2")).isDisplayed();
              System.out.println("Item2 element is displayed");
              driver.findElement(By.linkText("Item2")).click(); 
              } catch(NoSuchElementException e) { 
              System.out.println("--WARNING--The Item2 element is not displayed"); 
              } finally{ 
              System.out.println("Now Add Item2 to the Cart"); 
              }

try {
              driver.findElement(By.linkText("Item1")).isDisplayed();
              System.out.println("Item1 element is displayed");
              driver.findElement(By.linkText("Item1")).click(); 
              } catch(NoSuchElementException e) { 
              System.out.println("--WARNING--The Item1 element is not displayed"); 
              } finally{ 
              System.out.println("Now Add Item1 to the Cart"); 
              }

And it's working well. But i want to know if it's possible to create a variable for the element "Item1" and "Item2" The goal is use an object list at the begining of my code and then use only the object inside thr try catch block.

Something like:

String I1;// for Item1 String I2;// for Item2

And the use them as

try {
              driver.findElement(By.linkText("I1")).isDisplayed();
              System.out.println("Item1 element is displayed");
              driver.findElement(By.linkText("I1")).click(); 
              } catch(NoSuchElementException e) { 
              System.out.println("--WARNING--The Item1 element is not displayed"); 
              } finally{ 
              System.out.println("Now Add Item1 to the Cart"); 
              }

So is it possible or is it going to complicate my code. My goal is if one day the Item name change, i just want to modify the variable and not going through all the code and replace one by one.

Thank you for help

You can use a method to do so:

public void testElement(string text)
{
    try {
        driver.findElement(By.linkText(text)).isDisplayed();
        System.out.println(text + " element is displayed");
        driver.findElement(By.linkText(text)).click(); 
    } catch(NoSuchElementException e) { 
        System.out.println("--WARNING--The " + text + " element is not displayed"); 
    } finally{ 
        System.out.println("Now Add " + text + " to the Cart"); 
    }
}

testElement("I1");
testElement("I2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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