【问题标题】:Webdriver - Unable to locate element (Java)Webdriver - 无法定位元素(Java)
【发布时间】:2016-09-07 15:22:19
【问题描述】:

我是 Selenium 和 WebDriver 的新手。 我有这个 HTML:

<input id="undefined-undefined-Jobsubject-5546" type="text" value="" data-test="testing-job-subject" style="padding: 0px; position: relative; width: 100%; border: medium none; outline: medium none; background-color: transparent; color: rgb(255, 255, 255); cursor: initial; font: inherit; height: 100%; box-sizing: border-box; margin-top: 14px;"/>

我有这个代码:

driver.findElement(By.xpath("//input[@data-test='testing-job-subject']"));

但错误是:

org.openqa.selenium.NoSuchElementException:无法定位元素://input[@data-test='testing-job-subject']

我也试过这个:

driver.findElement(By.xpath("//*[starts-with(@id,'undefined-undefined-Jobsubject')]"));

因为id中的数字是生成的,所以不能取By.id(....),但是同样的错误。 是的,我在代码中有超时,所以元素在页面上。

问题出在哪里?谢谢

【问题讨论】:

    标签: java selenium


    【解决方案1】:

    如果您收到NoSuchElementException 作为您提供的异常,可能有以下原因:-

    • 可能当您要查找元素时,它不会出现在DOM 上,因此您应该执行WebDriverWait 以等待元素可见,如下所示:-

      WebDriverWait wait = new WebDriverWait(driver, 10);
      WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[data-test='testing-job-subject']")));
      
    • 这个元素可能在任何frameiframe 中。如果是,您需要在找到以下元素之前切换 frameiframe :-

      WebDriverWait wait = new WebDriverWait(driver, 10);
      
      //Find frame or iframe and switch
      wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("your frame id or name"));
      
      //Now find the element 
      WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[data-test='testing-job-subject']")));
      
      //Once all your stuff done with this frame need to switch back to default
      driver.switchTo().defaultContent();
      

    【讨论】:

    • 我尝试了第一个原因,但仍然没有,只是另一个错误:“org.openqa.selenium.TimeoutException:预期条件失败:等待 By.cssSelector 定位的元素的可见性:输入 [数据- test='testing-job-subject'](以 500 MILLISECONDS 间隔尝试了 10 秒)“并且没有框架或 iframe :/
    • 那么如何保证你没有frame或者iframe呢??
    • @Mephy 你确定你在这里为链接元素提供了正确的 HTML 代码吗?并确保该元素在页面上手动可见..
    【解决方案2】:

    试试这个:

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("input[data-test='testing-job-subject']")));
    

    【讨论】:

      【解决方案3】:

      这应该适合你。

      driver.findElement(By.cssSelector("id*='Jobsubject'"));
      

      【讨论】:

        猜你喜欢
        • 2012-04-27
        • 2016-04-15
        • 2016-12-10
        • 2018-09-30
        • 1970-01-01
        • 2014-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多