Selenium is struggling to identify the XPath displayed on the developer tools

https://i.stack.imgur.com/enl7F.jpg

https://i.stack.imgur.com/LNQW9.jpg

I am currently facing an issue with validating the visibility of a comment I posted on my profile. The comment appears on my wall and profile feeds, but Selenium is unable to recognize it. Despite being able to view the xpaths in devtools, I keep encountering the following error within Selenium:

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of proxy element.

Here is where the locator is defined in 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;

And here is how it's defined in 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;

The functions in my actions file are as follows:

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);
}

If I remove the waits, I encounter the following error:

Org.openqq.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression.

For more information on the app, visit

Answer №1

If you want to improve your xpath, it might be beneficial to search by text for better robustness.

To achieve this, consider having your test generate a random string before making the call:

@Test public void should_add_review()
{
  String randomReviewText = createRandomReview();
  postReview(randomReviewText);
  checkReviewIsDisplayed(randomReviewText);
}

public String createRandomReview()
{
  String random = UUID.randomUUID().toString();
  String shortenedRandom = random.substring(random.length() - 10);
  return shortenedRandom;
}

public void postReview(String shortenedRandom) {
    js.executeScript("window.scrollBy(0,450)", "");
    reviewLocators.firstReviewInput.clear();
    reviewLocators.firstReviewInput.sendKeys(shortenedRandom);
    reviewLocators.firstReviewInput.sendKeys(Keys.ENTER);
}

If for some reason obtaining the text is not possible, or if you cannot modify the test steps to include the text, you can still locate an element using an explicit locator. In the case of the specified app example, to retrieve the latest comment (last) on the most recent post (top), you could use the following XPATH:

//div[@class='body-content-col'][1]//div[@class='post-comment-article group'][last()]

This XPATH selection would look something like this:

@FindBy(how=How.XPATH ,using="(//div[@class='body-content-col'][1]//div[@class='post-comment-article group'][last()]")                      
public WebElement firstPostLastComment;

https://i.stack.imgur.com/6kyG2.png

Answer №2

It's recommended to utilize relative xpath instead of absolute ones for improved flexibility. Here's a simple example:

Let's say your comment is:

"Sample Comment"

You can find it using the following method:

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

This is just a basic illustration, you may explore more effective XPath locators.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activating RSpec slumber

Currently, I am in the process of writing a feature test to validate an edit action. It's a bit puzzling to me because when I run RSpec normally, it does not show what I expect. However, when I use the save_and_open_page command, it reveals that the e ...

Retrieve an element using Selenium's find_element

While working with find_element_by() in Selenium version 3.5, I found that the syntax for find_element has changed. There are now two ways to specify elements: using find_element(By.ID, "id-name") and find_element("id", "id-name& ...

Hover over Selenium WebDriver 2 in Java

I have been working on a project for the public site preview.harriscounty.org, and I am facing an issue with mousing over the markers in the right pane. Despite my efforts, I have not been successful in achieving this task. Whenever I mouse over a marker, ...

What is the best way to resize a primefaces inputTextArea to match the length of the

I am currently working on improving the appearance of <p:inputTextArea/>. When the page loads, I notice: And when I click on that TextArea: Here is the code: <p:inputTextarea rows="6" value="#{bean.object.value}" style="width: 100%;" /> Is ...

Automate sign-in across various browsers using Selenium

For the past 48 hours, I've been struggling with a problem that I can't seem to solve. The task at hand involves logging into multiple browsers on various machines for the same website. It's a time-consuming process, so I've decided to ...

I need help finding the P tag in the provided HTML code by using Xpath. Any advice is greatly appreciated!

I'm trying to assert **"sorry you can't Sorry, you do not have access to the requested page** but I'm unable to reach there.. Currently, I've managed to get here: //*[@id="page"]/child::div/following-sibling::section/ What i ...

Python script for extracting odds data from nowgoal's website by scraping the links

I am currently working on extracting the odds from Nowgoal. To start, I need to obtain the links for each match using a combination of Selenium and Beautiful Soup. My goal is not to retrieve links for all matches, but rather utilize an input text file whic ...

Is it possible to utilize Python and WebDriver to Assert/Verify the Presence of an Element

I'm a bit confused by the transition from Selenium to WebDriver and the differences in their respective documentation. The documentation mentions using Assert vs Verify, like AssertElementPresent, when discussing test design considerations. However, a ...

Encountered an issue while attempting to install a Chrome extension using Python with selenium

I want to automate the installation of a Chrome extension using Python Selenium. Whenever I try to click the "Add to chrome" button, a pop-up appears with options to "Add extension" or "Cancel". Despite trying to select "Add extension", I keep encountering ...

Ways to execute a singular python function concurrently on multiple occasions

I am looking to run a Python function in parallel 100 times. Can anyone provide the code snippet to achieve this? from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium import webdriver from selenium.webdriver.chrome ...

The current project does not support the feature you are trying to use when calling getWindowHandles()

Currently, I am utilizing Appium version 1.4.16.1, Selenium 2.53.0, and java-client 2.1.0 An issue has arisen where an error message is displayed: "org.openqa.selenium.WebDriverException: Not yet implemented. To assist us in resolving this issue, plea ...

Inquiry Regarding Utilizing Jenkins for Publishing JUnit Test Results

While working with Jenkins pipeline, I have a question about the JUnit command. Once executed during the build process, does it store the test results even if the JUnit reports directory is deleted? If so, where does Jenkins retrieve the deleted JUnit re ...

Using ChromeDriver to Maximize Browser Window

I have attempted to execute the F11 command in ChromeDriver, but it does not seem to acknowledge it. Whenever I manually press F11, Chrome enters fullscreen mode without any issues. However, when I send the F11 command through ChromeDriver, nothing happens ...

I keep encountering crashes with Firefox and receiving a ConnectionResetError while utilizing Python with Selenium

I've recently started working on a Python script that is designed to navigate through web pages and extract necessary data. During my research, I came across a code snippet that utilizes the Selenium library for internet navigation. However, when I ...

Implementing Conditional Statements in Date-picker with Selenium WebDriver using Python

As a newcomer to Python/Selenium, I am attempting to construct a statement that will execute an alternative action when the specified element cannot be located. Below is the code snippet in question. pickActiveDay = driver.find_element_by_xpath('//di ...

"Strategies for using Selenium in Python to simulate clicks without relying on class, id, or name attributes

I am currently attempting to locate the "X" button and click on it, but I am struggling to find a way to do so. Below is the HTML code for the element: <div style="cursor: pointer; float:right; border-radius: 3px; background-color: red; font-size: ...

Implementing Serialization of Java Objects to JSON and Sending them through a Servlet Filter

In my current setup, I have a javax.servlet.Filter that is responsible for checking if the client has permission to access an API REST resource. @Component public class AuthorizationRequestFilter implements Filter { public static final String AUTHORI ...

Getting the text from an element following the utilization of driver.find_elements_by_id

Currently, I am attempting to extract the information from a table by following these steps: from selenium import webdriver driver = webdriver.Chrome() driver.get("https://fortnitetracker.com/events/epicgames_S11_CC_Contenders_EU") player = driver.find_ ...

Transforming an array of HashMaps into a JSON object within a servlet and showcasing it on a JSP page

Looking to extract all table rows and store them in an array of hashmaps, then convert them into a JSON object to be sent to a JSP page using Ajax and jQuery. Struggling with displaying the content on the JSP page. I've written the code below but need ...

The click function is not compatible with InternetExplorerDriver in Selenium

I've been busy creating numerous tests for a ASP .NET Webforms application. My tool of choice is Selenium with InternetExplorerDriver. However, I'm encountering an issue that's got me stumped. Every now and then, when I try to use the "clic ...