selenium - Selenium 总是给出 org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:
问题描述
文字“恭喜!” 只有在交易成功时才会出现在网站上。
我正在尝试使用 JavascriptExecutor 捕获此元素的文本,因为类型设置为隐藏但 selenium 始终显示:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@class='form-header']//div[contains(text(),'Congratulations')]"}
(Session info: chrome=85.0.4183.121)
代码 1(不工作)
WebElement ele = driver.findElement(By.xpath(//div[@class='form-header']//div[contains(text(),'Congratulations')]));
JavascriptExecutor js = (JavascriptExecutor)driver;
String text = (String)js.executeScript("return arguments[0].value",ele);
System.out.println(text);
代码 2(不工作)
WebElement ele = driver.findElement(By.xpath(//div[@class='form-header']//div[contains(text(),'Congratulations')]));
JavascriptExecutor js = (JavascriptExecutor)driver;
String text = (String)js.executeScript("return arguments[0].innerHTML",ele);
System.out.println(text);
这部分的HTML代码如下:
<input id="hdnWindowLocationHost" name="hdnWindowLocationHost" type="hidden" value="/" data-value="themes/custom">
<div id="sgw" class="sgw SGW-header">
</div>
<div class="page">
<div class="content">
<div class="form">
<div class="form-header">
<div class="headline">Congratulations!</div>
Your password has been reset. Please log in below with your Username and password.
</div>
解决方案
由于元素是动态元素,因此要识别您需要诱导WebDriverWait的元素visibilityOfElementLocated()
,您可以使用以下任一Locator Strategies:
使用cssSelector:
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.form-header > div"))).getText());
使用xpath和
text()
:System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='form-header']/div[text()='Congratulations!']"))).getText());
使用xpath和
contains()
:System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='form-header']/div[contains(., 'Congratulations')]"))).getText());
推荐阅读
- deep-learning - nltk.download("wordnet") 完成了什么
- python - pytest 和 python 测试:报告为 python 函数编写的测试用例
- core-data - 更新 NSHostingView 的关于单元重用的 SwiftUI 视图
- django - DRF如何获取按类别分组的项目
- email - 如果收到正确的触发器,有没有办法设置电子邮件地址以发送特定电子邮件?
- sockets - Socket编程:设置服务器,端口为80则运行,端口为其他则无法运行
- azure - Power 自动创建密码
- java - 如何使用 VirtualSticks 实际控制无人机
- java - HashMap的HashMap->输出问题
- expo - 无论 initialRegion 参数如何,MapView 都会在赤道上检索非洲地图?