首页 > 解决方案 > 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

标签: javaseleniumxpath

解决方案


我建议您使用相对 xpath 而不是绝对 xpath。以下是您的操作方法:

假设您的评论是:

“我的测试评论”

您可以通过以下方式定位:

browser.findElement(By.xpath(".//span[text()='My Test Comment']"));

这只是一个示例。您可以寻找更好的 XPath 定位器。


推荐阅读