我会使用几行来处理文本——<br> 元素和包含部分文本的元素有点棘手:
// first, get all the text by locating div element
string allText = driver.findElement(By.id("login_credentials")).getText();
// then get H4 text so we can remove this string
string textToRemove = driver.findElement(By.xpath("//div[@id='login_credentials']/h4")).getText();
// remove unwanted "Accepted usernames are:" text
string filteredText = allText.Replace(textToRemove, "");
// split filteredText on newline regex so we can get line items including 'standard_user'
string[] textArray = filteredText.split("\\r?\\n");
// get standard_user text by getting first item in the split array
string standardUserText = textArray[0];
此代码的最后 3 行可以简化,但我写了更长的版本,以便我们了解每个步骤中发生的情况。
allText 评估后的变量应该等于Accepted usernames are: standard_user locked_out_user problem_user performance_glitch_user。
一旦我们删除出现在h4 元素中的Accepted usernames are: 文本,filteredText 就等于standard_user locked_out_user problem_user performance_glitch_user,每个项目都由换行符分隔,\r 或\n 字符——我们使用处理这两种情况的正则表达式..
我们将filteredText 拆分为\n 字符,因此我们得到一个数组,如下所示:
[ "standard_user", "locked_out_user", "problem_user", "performance_glitch_user" ]
然后,我们可以调用textArray[0] 来获取列表中的第一项,应该是standard_user。