硒在找到第一元素的前兄弟元素时永远悬挂

时间:2016-12-30 05:45:55

标签: java selenium selenium-webdriver

我试图从同一个元素中获取前面的元素。但由于webelement是第一个webelement,没有前兄弟元素,这个过程永远挂起。 当我试图从另一个webelement(而不是使用驱动程序)中找到webelements时,隐式等待也不起作用。

@BeforeTest
public void init(){
    driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS);
    driver.get("https://account.box.com/login");
}


    @Test
public void testWebElem(){
    WebElement source = driver.findElement(By.xpath(".//*[@id='login-form']/div/h2"));
    System.out.println(getPositionOfWebElem(source));
}


private int getPositionOfWebElem(WebElement elem){
    String xpathExpressionFollowing = "./following-sibling::*";
    System.out.println("xPath Expression :: " + xpathExpressionFollowing);
    List<WebElement> elemsFollowing = elem.findElements(By.xpath(xpathExpressionFollowing));
    printWebelems(elemsFollowing);
    String xpathExpression = "./preceding-sibling::*";
    System.out.println("xPath Expression :: " + xpathExpression);
    List<WebElement> elemsts = elem.findElements(By.xpath(xpathExpression));
    printWebelems(elemsts);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

减少你的隐式等待,因为2000秒是非常长的等待!否则webdriver会等待2000秒才能找到前面不存在的元素!BTW如果你喜欢4位整数,请使用TimeUnit.MILLISECONDS

Snippet下面为我工作

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;

public class Test22{

WebDriver driver;

@Before
public void init(){
 driver = new FirefoxDriver();
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 driver.get("https://account.box.com/login");
}

@Test
  public void testWebElem(){
WebElement source = driver.findElement(By.xpath(".//*[@id='login-form']/div/h2"));
System.out.println(getPositionOfWebElem(source));
}


private int getPositionOfWebElem(WebElement elem){
String xpathExpressionFollowing = "./following-sibling::*";
System.out.println("xPath Expression :: " + xpathExpressionFollowing);
List<WebElement> elemsFollowing = elem.findElements(By.xpath(xpathExpressionFollowing));
System.out.println(elemsFollowing.size());
String xpathExpression = "./preceding-sibling::*";
System.out.println("xPath Expression :: " + xpathExpression);
List<WebElement> elemsts = elem.findElements(By.xpath(xpathExpression));
System.out.println(elemsts.size());
return 0;
}

}