[英]How to Create variable for an element in a webpage using webdriver
i'm using webdriver to find element in a webpage. 我正在使用webdriver在网页中查找元素。 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.
但是我想知道是否可以为元素“ Item1”和“ Item2”创建变量。目标是在代码开始时使用对象列表,然后仅在try catch块内使用对象。
Something like: 就像是:
String I1;// for Item1 String I2;// for Item2 字符串I1; //对于Item1字符串I2; //对于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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.