I'm new in Selenium and WebDriver.
I have this HTML:
and I have this code:
driver.findElement(By.xpath("//input[@data-test='testing-job-subject']"));
but the error is:
org.openqa.selenium.NoSuchElementException: Unable to locate element: //input[@data-test='testing-job-subject']
I tried also this:
driver.findElement(By.xpath("//*[starts-with(@id,'undefined-undefined-Jobsubject')]"));
because the number in id is generated, so I can't take the By.id(....), but the same error.
And yes,I have in the code the timeouts,so the element is on the page.
Where is the problem? Thanks
解决方案
If you are getting NoSuchElementException as your provided exception, There may be following reasons :-
May be when you are going to find element, it would not be present on the DOM, So you should implement WebDriverWait to wait until element visible as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[data-test='testing-job-subject']")));
May be this element is inside any frame or iframe. If it is, you need to switch that frame or iframe before finding the element as below :-
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();