Selenium: test if element contains some text

2019-06-14 23:21发布

问题:

With Selenium IDE, how can I test if an element's inner text contains a specific string? For example:

<p id="fred">abcde</p>
'id=fred' contains "bcd" = true)

回答1:

The Selenium-IDE documentation is helpful in this situation.

The command you are looking for is assertText, the locator would be id=fred and the text for example *bcd*.



回答2:

It can be done with a simple wildcard:

verifyText
id="fred"
*bcd*

See selenium IDE Doc



回答3:

You can also use:

assertElementPresent
css=p#fred:contains('bcd')


回答4:

Are you able to use jQuery if so try something like

$("p#fred:contains('bcd')").css("text-decoration", "underline");


回答5:

It seems regular expressions might work:

"The simplest character set is a character. The regular expression "the" contains three
character sets: "t," "h" and "e". It will match any line with the string "the" inside it.
This would also match the word "other". "

(From site: http://www.grymoire.com/Unix/Regular.html)

If you are using visual studio there is functionality for evaluating strings with regular expressions of ALL kinds (not just contains):

using System.Text.RegularExpressions;

Regex.IsMatch("YourInnerText", @"^[a-zA-Z]+$");

The expression I posted will check if the string contains ONLY letters.

Your regular expression would then according to my link be "bcd" or some string you construct at runtime. Or:

Regex.IsMatch("YourInnerText", @"bcd");

(Something like that anyway)

Hope it helped.



回答6:

You can use the command assertTextPresent or verifyText