如何让selenium网络驱动程序执行或使用最后一个xpath



我有一个名为click button的方法,在那里我将有多个包含X路径的try-catch,那么如何知道驱动程序最近执行了哪个X路径呢?

public void actions(String action, String param, Webdriver driver){
switch(action){
case "Click Button":
clickButton(driver, param);
}
}
public void clickButton(Webdriver driver, String param){
try{
if (param.equalsIgnoreCase("Search")) {
WebElement waittext = driver.findElement(By.xpath(("xpath for search button")));
Actions actions = new Actions(driver);
actions.moveToElement(waittext).build().perform();
waittext.click();
return;
}catch(Exception e){
System.out.println(e);
}
try{
if (param.equalsIgnoreCase("Save")) {
WebElement waittext = driver.findElement(By.xpath(("xpath for save button")));
Actions actions = new Actions(driver);
actions.moveToElement(waittext).build().perform();
waittext.click();
return;
}catch(Exception e){
System.out.println(e);
}
so on....
}

像这样,我会有很多尝试接球的机会。我的第一个想法是在每次尝试接球时都会返回X路径,但变化对我来说太大了,而且会花费很多时间,所以我在想,有没有什么方法可以让我通过驾驶员简单地获得最后或最近的X路径

public void actions(String action, String param, Webdriver driver){
switch(action){
case "Click Button":
clickButton(driver, param);
String recentlyUsedXpath = driver.getLastXpath(); //something like this I needed here.
}
}

我知道驱动程序不会有这样的方法:driver.getLastXpath((,但我希望如果有类似的东西,或者任何方式,我可以得到最近的X路径。

您正在从actions((方法调用clickButton((方法。在"actions(("方法中,为XPath添加另一个参数,并将该参数传递给"clickButton((",如下所示:

public void actions(String action, String param, Webdriver driver, String xpath){
switch(action){
case "Click Button":
clickButton(driver, param, xpath);
}
}

在"clickButton(("方法中,将该xpath传递给"findElement"语句,然后添加一个ArrayList来存储xpath,并尝试最小化"if"条件的数量,例如

public void clickButton(Webdriver driver, String param, String xpath){
List<String> xpathList = new ArrayList<>();
xpathList.add(xpath);
try{
if (param.equalsIgnoreCase("Search")) {
WebElement waittext = driver.findElement(By.xpath(xpath));
} else if(param.equalsIgnoreCase("Save")) {
WebElement waittext = driver.findElement(By.xpath(xpath));
}
Actions actions = new Actions(driver);
actions.moveToElement(waittext).build().perform();
waittext.click();
return;
}catch(Exception e){
System.out.println(e);
}
}

如果您需要使用最后一个xpath,那么您可以通过使用index从"xpathList"arraylist中获取它。

现在您正在使用字符串作为元素的引用,因为您发现这很难维护,需要进行大量更改。

一个快速而肮脏的解决方案是只将xpath传递给有问题的方法,而不是转换它,这意味着您将在上游获得该xpath引用。

另一个可能对您有所帮助的关键见解是,您实际上可以传递对WebElement本身的引用。以一种方法为例:

public void clickButton(Webdriver driver, WebElement element) {
try{
Actions actions = new Actions(driver);
actions.moveToElement(element).build().perform();
element.click();
return;
}catch(Exception e){
System.out.println(e);
}
}

这样做的目的更加明确,维护和调试也更加容易。现在,你可以用这样的东西来称呼它

clickButton(driver, searchButton);

其中:

WebElement searchButton = driver.findElement(By.xpath(searchButtonXpath));

现在,您可以将这些细节进一步抽象为";页面";类,它将具有对您网站元素的所有引用,并将使其更容易实现,这被称为页面对象模型,是非常鼓励您测试的设计模式,因为它将在未来为您节省大量时间。

最后,我建议查看WebDriver的等待时间,这样在定位元素和页面刷新之间就可以避免时间问题。

最新更新