2016-09-07 178 views
0

我是Selenium和WebDriver中的新成员。 我有这样的HTML:Webdriver - 无法找到元素(Java)

<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: Unable to locate element: //input[@data-test='testing-job-subject']

我也试过这样:

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

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

问题在哪里?由于

回答

2

如果你正在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(); 
    
+0

我试过了第一个原因,但仍然没有,只是另一个错误: “org.openqa.selenium.TimeoutException:预期的条件失败:等待By.cssSelector定位的元素的可见性:input [data-test ='testing ](用500 MILLISECONDS间隔尝试10秒)“ 并且没有框架或iframe:/ – Mephy

+0

那么如何确保您没有框架或iframe? –

+0

@Mephy你确定你在这里提供了链接元素的正确的HTML代码?并确保该元素在页面上可手动显示。 –

0

试试这个:

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

我觉得下面应该

你driver.findElement工作(By.cssSelector(” ID * = 'Jobsubject'“));