0

I try with following xpath

driver.findElement(By.xpath("//div[contains(@class,'ReactTags__selected')]//span[1]/text()"));

but get following error

"org.openqa.selenium.InvalidSelectorException: invalid selector: The result of the xpath expression "//div[contains(@class,'ReactTags__selected')]//span[2]/text()" is: [object Text]. It should be an element."

<div class="ReactTags__selected">
        <span class="tag-wrapper ReactTags__tag" style="opacity: 1; cursor: auto;" draggable="true">
        "TestName"
        <a class="ReactTags__remove">×</a>
        </span>
</div>
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352

3 Answers3

0

Please try the below Xpath.

Hope it helps

//div[contains(@class,'ReactTags__selected')]//span[2]/a/text()
vigneshwaran m
  • 351
  • 2
  • 12
  • There aren't two `` tags in the html ant `text()` is not supported by Selenium. – Guy Mar 12 '20 at 13:33
0

text() in the xpath returns text node, Selenium doesn't support it. Locate the element and use getText() to get the text

WebElement element = driver.findElement(By.xpath("//div[contains(@class,'ReactTags__selected')]//span[1]"));
String text = element.getText();
Guy
  • 46,488
  • 10
  • 44
  • 88
0

As the parent element contains the attribute draggable="true" invariably it's a dynamic element, precisely React element. Additionally as the text TestName is a Text Node you need to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • cssSelector:

    System.out.println(((JavascriptExecutor)driver).executeScript('return arguments[0].firstChild.textContent;', new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.ReactTags__selected > span.tag-wrapper.ReactTags__tag")))).toString());
    
  • xpath:

    System.out.println((String)((JavaScriptExecutor)driver).executeScript("return arguments[0].firstChild.textContent;", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='ReactTags__selected']/span[@class='tag-wrapper ReactTags__tag']")))));
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352