是否可以确定Selenium WebElements的html代码顺序

时间:2017-12-21 16:21:43

标签: java sorting selenium

是否有可能在html代码中找出一个WebElement是否位于另一个WebElement之前?

更一般的是,是否可以根据html代码中的顺序对/* <html> <body> <div> <div>first</div> </div> <div>second</div> </body> </html> */ public int compare(WebElement a, WebElement b) { return -1; // if a=first, b=second return 0; // I'm not really interested in corner cases return 1; // if a=second, b=first } 个对象的集合进行排序? (注意:排序很多元素实际上并不是我的意图)

XPath

preceding::中,您拥有following::WebElement轴,但在我的情况下,我已经拥有<asp:Label runat="server" ID="Label1" /> protected void Page_Load(object sender,EventArgs e) { Label1.Text = "Your Value"; } 个对象,我想确定它们的相对顺序。

3 个答案:

答案 0 :(得分:0)

我没有对此进行过测试,我即时编码:

public WebElement firstInList(WebElement a, WebElement b) {

    WebElement found = null;
    List<WebElement> all = driver.findElements(By.xpath("//*");

    for (WebElement test : all) {
        if (test.equals(a)) {
            found = a;
            break;
        } else if (test.equals(b)) {
            found = b;
            break;
        }
    }

    return found;

}

答案 1 :(得分:0)

为了使用两个不同的IWebElements将是一个痛苦 - 很难并且需要花费很多时间来获取信息以发现html节点并知道每个节点在哪里 - &gt;并且最终说谁是第一个,谁是第二个。

我的消化是使用两个选择器:cssSelector或Xpath。它们都能够在自身内部混合多个选择条件,当您尝试使用findElements返回IWebElements列表时,它将根据html顺序返回。这意味着,fiers html节点将成为列表中的第一个元素。

一个例子(在c#中,抱歉,我不知道java)

public bool IsATheFirstElement(string aXPathSelector, string bXPathSelector)
{
    // Creates a xpath to find both elements: A and B
    var generalXPath = aXPathSelector + " | " + bXPathSelector;

    // Get a list of elements containing A and B, in HTML order
    var ab = _driver.FindElements(By.XPath(generalXPath));

    // Get the A element
    var a = _driver.FindElement(By.XPath(aXPathSelector));

    // Returns a bool value that checks if a is the first element or not
    return ab.First() == a;
}

答案 2 :(得分:0)

这种解决方案相当“蛮力” 它会查找a之后的所有元素,并查看b是否在那里。

public int compare(WebElement a, WebElement b) {
    if(a.equals(b)){
        return 0;
    }
    List<WebElement> afterA = a.findElements(By.xpath("descendant::* | following::*"));
    if(afterA.contains(b)) {
        return -1;
    } else {
        return 1;
    }
}
相关问题