Selenium: find element by visible Text

2020-07-22 20:13发布

问题:

In the html page i have the following balise:

<button class="....." data-toggle="dropdown">
Text: Title of the button                        
<span class="....."/>
</button>

And I want to detect this buton By the visible text Text: Title of the button the problem is that i'm trying to detect it using the following Xpath

.//*[contains(text(),"Text: Title of the button")]

But it does'nt work. How i can detect this button?

FYI: I can't detect it using class because there more than one matching node with this class.

回答1:

contains(text(), '...') only evaluates first text node child from current context element. This shouldn't be any problem for sample element you posted (see demo, but it wouldn't work with the following element for example, because the first text node inside button is the newline located before span :

<button class="....." data-toggle="dropdown">
<span class="....."/>
Text: Title of the button                        
</button>

To evaluate all text node children of current context element, use the following form instead :

.//*[text()[contains(.,"Text: Title of the button")]]

demo

The above XPath tests individual text node if it contains certain text.



回答2:

Hi please do it like below

By.xpath("//button[contains(text(),'Text: Title of the button')]")
please put Text: Title of the button in single quote.
Also if more html source code is provided then i can come up with a better locator stratgey

Also you can do it on the basis of Class name as well or by talking attribute data-toggle="dropdown" in xpath as well like //*[@data-toggle='dropdown']

// take class name of the button in list

List<WebElement> buttons= driver.findElements(By.className("className"));
Now you can select your concerned button on the basis of index (in java index starts 
form zero)