Helping Hands
Helping Hands

Reputation: 5396

Xpath is unable to find text

HTML CODE

<div class="filterInfoContainer">
    <div class="result-header-right">
      <div class="show-soldout">
        <label for="soldout-switch">Display sold out products</label>
        <label class="switch xs">
          <input type="checkbox" name="soldout-switch" id="soldout-switch">
          <div class="switch-slider"></div>
        </label>
      </div>
      <div class="sort-by">Sorted by:
        <select id="sortByDropdown">
          <option value="popularity">Popularity</option>
          <option value="price">Lowest price</option>
          <option value="discount">Highest discount</option>
          <option value="year">Latest release</option>
        </select>
      </div>
    </div>
      Showing 323 products
    <div class="clearfix"></div>

  </div>

Xpath I tried

.//*[@id='filterInfo']/div
.//*[@id='filterInfo']/div/text()

I want to get text Showing 323 products but my xpath does not return me. As this text has no particular div I am getting difficulty to get it.

Selenium code I tried

 driver.findElement(By.xpath(".//*[@id='filterInfo']/div"));

 driver.findElement(By.xpath(".//*[@id='filterInfo']/div/text()"));

Getting exception : Invalid Selector

Upvotes: 3

Views: 1850

Answers (3)

Andersson
Andersson

Reputation: 52665

In Selenium XPath expression should return webelement only while your second XPath intend to return text node. That's why you get Invalid Selector exception.

Also I see no div with id="filterInfo" in provided HTML sample. If you need to get "Showing 323 products", try below code:

driver.findElement(By.xpath("//div[@class="filterInfoContainer"]/div[1]")).getText();

Considering updated HTML sample, another approach for case when you need to get text excluding text of child elements:

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("return document.evaluate('//div[@class=\"filterInfoContainer\"]/div/following-sibling::text()', document, null, XPathResult.ANY_TYPE, null).iterateNext().textContent;");

Upvotes: 0

Lahiru
Lahiru

Reputation: 1688

You can get Showing 323 products with //div/text(). Basically it will return the text that is not wrapped in tags. Please refer this example.

So in your case:

//div[@class='filterInfoContainer']/text()

http://www.xpathtester.com/xpath/d06b22fb023db960d8fc619485759127

Upvotes: 1

Kims
Kims

Reputation: 425

Try using developer tools in Chrome to find the "filterInfo" component via xpath first, and see if that works.

Upvotes: 0

Related Questions