简体   繁体   中英

Locating elements using text

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?

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')]"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM