繁体   English   中英

如何使用WebDriver为网页中的元素创建变量

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

我正在使用webdriver在网页中查找元素。 该网页包含不同的元素。

所以要找到一个元素,我使用以下代码:

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"); 
              }

而且运作良好。 但是我想知道是否可以为元素“ Item1”和“ Item2”创建变量。目标是在代码开始时使用对象列表,然后仅在try catch块内使用对象。

就像是:

字符串I1; //对于Item1字符串I2; //对于Item2

并将它们用作

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"); 
              }

所以有可能还是会使我的代码复杂化。 我的目标是,如果某天项目名称更改,我只想修改变量,而不要遍历所有代码并一一替换。

谢谢你的帮助

您可以使用一种方法来做到这一点:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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