1

In the following HTML I need to be able to select the element using the text located within, "SELECT PRODUCT".

<div style="font-family: franklin-gothic-urw; font-weight: 400; font-style: normal; font-size: 19px; opacity: 1; color: rgb(255, 255, 255);">SELECT&nbsp;PRODUCT</div>

All resources lead me to something like this:

driver.findElement(By.cssSelector("div[textContent='SELECT PRODUCT'])

which does not work. I've tried various other xpaths and cssSelector and I can't seem to get it to locate the element.

Locating the element by it's absolute path works, but it's brittle and we don't want to locate it like that:

html/body/div[3]/div[1]/div/div[3]/div/div/div/div/div[1]/div/div/div/div/div[2]/div[2]/div/div/div/div/div[2]/div

Selecting by style, aswell, will not work, as there are multiple elements on the page with the same format.

I have tried to find an answer to this for a long while now. What is the correct way to go about locating an element by text?

jagdpanzer
  • 693
  • 2
  • 10
  • 35

1 Answers1

1

Locate the element by XPath:

driver.findElement(By.xpath("//div[. = 'SELECT PRODUCT']"));

Or, as a workaround to tackle the &nbsp; inside the text:

driver.findElement(By.xpath("//div[starts-with(., 'SELECT') and contains(., 'PRODUCT')]"));
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • The above does not seem to work as is. What does the "." stand for in the xpath? If it makes any difference, I'm required to do my work in Java. – jagdpanzer Oct 26 '15 at 17:54
  • 1
    @jagdpanzer `.` refers to element's text in this case. The solution, I'm pretty sure, would eventually help you. I suspect the ` ` space is giving us problems here, please see: http://stackoverflow.com/questions/247135/using-xpath-to-search-text-containing. – alecxe Oct 26 '15 at 18:03
  • The above is still giving me issues. I'm currently reading through the link. I have a really finicky web application - any really unorthodox methods are usually the ones that work. Selecting by text is the top of my priorities now. I'll keep this updated. Thanks for the help so far. Currently trying in the FirefoxDriver if that makes any difference. – jagdpanzer Oct 26 '15 at 18:45
  • 1
    `//div[contains(.,'SELECT PRODUCT')]` worked, but now my pass/fail check isn't picking up the text it identified it by. Oi vey.. – jagdpanzer Oct 26 '15 at 19:00