执行时无法找到xpath

问题描述 投票:0回答:3

下面的代码用于使用WebDriver测试拖放功能。我面对代码的麻烦在于它无法检测到XPath。

public class draganddrop
{
    public static void main(String[] args) throws InterruptedException
    {
        // opening site for practicing user interaction by mouse using webdriver and action class
        WebDriver driver = new ChromeDriver();
        String URL = "http://www.dhtmlx.com/docs/products/dhtmlxTree/index.shtml";
        driver.get(URL);

        // It is always advisable to Maximize the window before performing DragNDrop action
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
        WebElement From = driver.findElement(By.xpath(".//*[@id='treebox1']/div/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[4]/span"));
        WebElement To = driver.findElement(By.xpath(".//*[@id='treebox2']/div/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[4]/span"));
        Actions builder = new Actions(driver);
        Action dragAndDrop = builder.clickAndHold(From).moveToElement(To).release(To).build();
        dragAndDrop.perform();

        Thread.sleep(2000);
    }
}

错误消息

线程“main”中的异常org.openqa.selenium.NoSuchElementException:没有这样的元素:无法定位元素:{“method”:“xpath”,“selector”:“.//* [@ id ='treebox1'] / DIV /表/ tbody的/ TR [2] / TD [2] /表/ tbody的/ TR [2] / TD [2] /表/ tbody的/ TR [1] / TD [4] /跨度“}

selenium xpath
3个回答
1
投票

我不知道是什么导致你到那个XPath,但根据源代码它似乎不正确。

更换

WebElement From = driver.findElement(By.xpath(".//*[@id='treebox1']/div/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[4]/span"));

对于

WebElement From = driver.findElement(By.xpath(".//*[@id='treebox1']"));

它应该能够在那之后检测到指定的div。


1
投票

这是一些有效的代码。我清理了一些你的代码,拿出了不必要的东西,等等。

driver.get("http://www.dhtmlx.com/docs/products/dhtmlxTree/index.shtml");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement from = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//span[text()='Thrillers'])[1]")));
WebElement to = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//span[text()='Bestsellers'])[2]")));
driver.findElement(By.xpath("//h2[text()='Live Demo']")).click(); // this moves the screen down
Actions builder = new Actions(driver);
builder.dragAndDrop(from, to).build().perform();

你应该对.implicitlyWait()做一些阅读。你不想按照自己的方式使用它,绝对没有那么大的超时。我建议你完全摆脱它,只使用明确的等待。

在代码开头等待这两个元素可能有点过分。如果你只是等待第一个,第二个很可能已经存在......但为了以防万一。

使用那么长的XPath会遇到麻烦。如果在该长XPath中页面上有任何更改,您的脚本将停止工作。对XPath和CSS选择器进行一些阅读,并学习如何有效地使用它们。它将使您的脚本更具弹性。

Actions,已经有一种dragAndDrop()方法。只需使用它而不是自己制作。

我不得不点击Live Demo标题。问题是当执行拖放操作时,屏幕会滚动,并且在页面滚动后显示的菜单会导致它无法正常工作。修复是在拖放之前滚动屏幕,以便源和目标都在屏幕上,而不是由顶部导航菜单等隐藏。还有其他方法滚动屏幕,但这一个工作正常。

你也想避免使用qazxsw poi。阅读qazxsw poi和qazxsw poi,了解如何使用它,如果你需要等待一些事情发生。您可以看到我在上面使用它作为示例。


0
投票

我只是隐式地改变了下面的等待是你修改的代码

Thread.sleep()
© www.soinside.com 2019 - 2024. All rights reserved.