java - Selenium 不会重新调整在 devtools 上显示的 XPath
问题描述
我正在尝试验证我在个人资料上发布的评论是否显示在我的墙上和个人资料提要中。评论总是被发布;但是,硒无法识别已发布的评论。xpaths 显示在 devtools 中,但我在 selenium 中收到以下错误:
org.openqa.selenium.TimeoutException:预期条件失败:等待代理元素的可见性。
这是 homeLocators 中的定位器:
@FindBy(how=How.XPATH ,using="(/html/body/main/div/section/div[2]/div/div[2]/div[2]/div/div/div[last()-1])/div[2]/div[2]‹")
public WebElement firstPostLastComment;
这是 profileLocators 中的定位器:
@FindBy(how=How.XPATH ,using="(/html/body/main/div/section/div[3]/div/div[2]/div[2]/div/div/div)[last()-1]/div[2]/div[2]")
public WebElement firstPostLastComment;
以下是我的操作文件中的函数:
public void postCommentProfile() {
js.executeScript("window.scrollBy(0,450)", "");
String random = UUID.randomUUID().toString();
String randomShortened = random.substring(random.length() - 10);
commentProfile = randomShortened;
profileLocators.firstPostCommentInput.clear();
profileLocators.firstPostCommentInput.sendKeys(randomShortened);
profileLocators.firstPostCommentInput.sendKeys(Keys.ENTER);
}
public void newCommentShowsOnWallAndProfile() throws InterruptedException {
navLocators.navProfile.click();
js.executeScript("window.scrollBy(0,450)", "");
new WebDriverWait(SeleniumDriver.getDriver(), 60)
.until(ExpectedConditions.visibilityOf(profileLocators.firstPostLastComment));
boolean flag = true;
String expectedText = commentProfile;
System.out.println("this is expected text in newCommentShows" + expectedText);
String profileActualText = profileLocators.firstPostLastComment.getText();
System.out.println("this is profile actual text in newCommentShows" + profileActualText);
if(!profileActualText.equals(expectedText)) {
flag = false;
System.out.println("flag false fired");
}
navLocators.navHome.click();
js.executeScript("window.scrollBy(0,450)", "");
new WebDriverWait(SeleniumDriver.getDriver(), 60)
.until(ExpectedConditions.visibilityOf(homeLocators.firstPostLastComment));
String wallActualText = homeLocators.firstPostLastComment.getText();
System.out.println("this is wall actual text in newCommentShows" + wallActualText);
if(!wallActualText.equals(expectedText)) {
flag = false;
}
Assert.assertTrue(flag);
}
如果我取消等待,我会收到以下错误:
Org.openqq.selenium.InvalidSelectorException:无效选择器:无法使用 xpath 表达式定位元素。
这是应用程序的链接 https://spbk.herokuapp.com/#/login
解决方案
我建议您使用相对 xpath 而不是绝对 xpath。以下是您的操作方法:
假设您的评论是:
“我的测试评论”
您可以通过以下方式定位:
browser.findElement(By.xpath(".//span[text()='My Test Comment']"));
这只是一个示例。您可以寻找更好的 XPath 定位器。
推荐阅读
- node.js - 使用 PM2 和 Vscode 进行调试
- python - 在 django 中使用迁移命令时如何解决值错误
- android - 在 Android 上从 c++ 获取唯一的设备标识符
- java - 在 Jenkins 管道中使用 Sonarqube 分析 Gradle Java 项目在 Jacoco 报告上引发异常
- apache-spark - 独立的 spark 会创建多少个 executor
- android - 如何在 Git 中合并两个分支(主分支和演示分支)代码
- laravel - 查询:多次指定表名
- java - 调用从对象 B 中保存另一个对象 (B) 的对象 (A)
- java - 如何从我的 Firebase 数据库中检索所有花瓶?
- java - Java 监听应用程序关闭