问题描述
我有一个简单的 HTML 网页,其中包含嵌套在一些 div 和 </form>
中的文本字段(我看不到 IFrame)。我确定我使用的是正确的 ID,但是在 IntelliJ 中运行代码时,它一直失败。这是元素的html。这是我得到的例外:
例外
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="loginLastName"]"}
以及我试图通过 selenium 定位的元素(文本字段)的 HTML:
HTML:
<input type="text" maxlength="32" minlength="2" required="" id="loginLastName" class="grv-input " aria-describedby="loginLastNameAria" pattern="(([ \-.']*)?[A-Za-z]+([ \-.']*)?)*">
在 java 代码中,我的浏览器正确加载到 http://google.com
等虚拟站点,但未能从我的相关站点中获取 elementId。我尝试使用 ID 和 XPATH(我从 Chrome 浏览器中获得):
Java
// get by ID
driver.findElement(By.id("loginLastName")).sendKeys("This is a test");
// get by XPATH
driver.findElement(By.xpath("//*[@id=\"loginLastName\"]")).sendKeys("dsdfdsfdsdsdsfdsgsdfgsdfdsg");
我还尝试添加延迟以确保组件有时间加载,但没有任何变化
webdriverwait wait = new webdriverwait(driver,100);
element = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginLastName")));
嵌套在两个 <divs>
和一个 <form>
内有关系吗?我是否必须遍历这些元素,才能深入了解这个或其他元素? (似乎过于复杂,尽管我对 selenium 的研究不多)。
告诉我!
解决方法
好的,看到您的页面后,我相信我知道问题所在。您尝试识别的“姓氏”字段位于两个嵌套的 shadow-root
元素中。除非您识别并告诉它在那里查看,否则硒不会查看影子根。尝试使用这样的代码:
JavascriptExecutor js;
WebElement shadowRootElement = js.executeScript('''return document.querySelector("refi-common-login-form").shadowRoot''');
WebElement shadowRootChild = js.executeScript('''return arguments[0].querySelector("refi-common-last-name").shadowRoot''',shadowRootElement);
shadowRootChild.findElement(By.id("loginLastName")).sendKeys("This is a test");
,
你可以试试下面的 Xpaths
#Get Xpath with combination
//input[@type='text' and @id='loginLastName']
#Xpath assuming there are multiple elements (DOM mentioning 1 of 2 elements)
(//input[@type='text' and @id='loginLastName'])[1]
#Get Xpath with another combination
//input[@type='text' and @aria-describedby='loginLastNameAria']
附录
List <WebElement> elementCheck = driver.findElements(By.xpath("<xpath of element>"))
if (elementCheck.size() == 0){
//Element not present when entered to the page
//Do something
}else {
//Do something
}