Webdriver - 无法定位元素(Java) [英] Webdriver - Unable to locate element (Java)
问题描述
我是Selenium和WebDriver的新手。
我有这个HTML:
I'm new in Selenium and WebDriver. I have this 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:无法找到element:// 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(.. ..),但同样的错误。
是的,我在代码中有超时,因此元素在页面上。
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.
问题出在哪里?谢谢
推荐答案
如果你得到 NoSuchElementException
作为你提供的例外,那里可能是以下原因: -
If you are getting NoSuchElementException
as your provided exception, There may be following reasons :-
-
可能在您要查找元素时,它不会出现在
DOM
,所以你应该实现WebDriverWait
,等到元素可见如下: -
May be when you are going to find element, it would not be present on the
DOM
, So you should implementWebDriverWait
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']")));
这个元素可能在任何框架内
或 iframe
。如果是,您需要在找到如下元素之前切换 frame
或 iframe
: -
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();
这篇关于Webdriver - 无法定位元素(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!