【问题标题】:Java Selenium findelement is not acknowledging an element that is on the pageJava Selenium findelement 不承认页面上的元素
【发布时间】:2019-05-25 06:23:06
【问题描述】:

如果我在 Chrome 中使用开发人员工具,并粘贴我的 By.name 语句,页面会准确地突出显示我要查看的内容。

下面是两个相邻的 java 语句:

driver.findElement(By.xpath("//input[@name='firstName']")).clear();
driver.findElement(By.xpath("//input[@name='shippingCost']")).click();

我将这两个并排放置,以排除驱动程序在它们来自的代码点以某种方式损坏。第一条语句确实清除了引用的文本框,但第二条语句返回 NoSuchElementError。如上所述,我也尝试过使用 By.name,我只是在追查为什么第二个每次都会引发错误。

我正在使用的页面是 EXTJS 单页网站,因此控件始终存在。我想使用 .getText().length() 来验证此框中现在是否有文本。

关于为什么我无法在可以使用我的 xpath 或名称选择器查看页面上的控件的页面上单击,甚至无法引用此控件的任何帮助。

---编辑将这些代码相关的图片添加到上述xpaths

Sorry, this is another place that doesnt work, [name='shippingTypeGroundDate']

This is the shippingcost location

And this is the working firstName location

【问题讨论】:

  • 用相关的 HTML 更新问题
  • 添加图片,直到我弄清楚如何获取 html 段。思想提取将是容易的部分,哈哈。

标签: google-chrome java selenium


【解决方案1】:

检查所选选择器中是否有重复元素。根据您的描述,名称字段按预期工作,并且您面临运输成本字段的问题。与所选选择器在同一页面上可能存在处于非活动状态的重复元素。

您可以使用以下 java code 获取当前元素的数量:

List<WebElement> listOfElements =driver.findElements(By.xpath("//input[@name='shippingCost']")); 
System.out.println("Number of elements:" +listOfElements.size());

如果上述解决方案不起作用,请尝试使用 javascriptexecutor ,即使该元素位于另一个元素之下,它也会执行这些操作。

【讨论】:

  • 好的,HTML 版本,根据要求。首先工作 xpath '
    '
  • 现在不工作的 xpath 段 '
    '(必须从图片编辑长度违规)
  • 我会尝试 javascript 方法(并学习它),因为当我按我的 By 字符串搜索时,编辑器只显示一个元素。
  • 刚刚尝试搜索,收到这个错误,就是这个问题的标题。 org.openqa.selenium.NoSuchElementException 当它试图找到页面上存在的控件时。它没有被任何东西隐藏,它在页面的开头,只是没有任何文本。当我尝试检查长度是否大于零时,我得到了上述异常。如果 javascript 执行解决了在 dom 问题上找不到的问题,我会报告。
【解决方案2】:

添加显式等待输入文本框被加载。然后尝试使用 Javascript 执行器单击文本框。有时 webdriver click 可能不起作用。

WebElement element = driver.findElement(By.xpath("//input[@name='shippingCost']"));
try {
        if (element.isEnabled() && element.isDisplayed()) {

                ((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
            } else {
                System.out.println("Unable to click on element");
            }
        } catch (StaleElementReferenceException e) {
            System.out.println("Element is not attached to the page document "+ e.getStackTrace());
        } catch (NoSuchElementException e) {
            System.out.println("Element was not found in DOM "+ e.getStackTrace());
        } catch (Exception e) {
            System.out.println("Unable to click on element "+ e.getStackTrace());
        }

【讨论】:

  • 感谢您提供此示例。我最初的问题不会让我通过第一行。问题是找不到该元素。忘记找到元素后我们可以做的所有其他事情,这些用于 shippingCost 和 shippingTypeGroundDate 的路径只会在代码看到它们时提供 NoSuchElementException 错误。
猜你喜欢
相关资源
最近更新 更多
热门标签