0

After logged in, there is a welcome "user name" message,

Source code

I want to write the xpath to capture that user. A few ideas I have tried:

//span[@id='WhoLoggedInUpdatePanel']//h1//br[contains(text(),'Welcome Sheikh')]

//h1[contains(text(),'"Welcome Sheikh"')]

None of those are working. Your suggestion would be very helpful.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Sheikh Rahman
  • 895
  • 3
  • 14
  • 29
  • Nothing in your example contains the text "Welcome Sheikh" - there are a LOT of space characters between the words ! Check out the normalize-space function - eg https://stackoverflow.com/questions/1829176/how-to-get-the-normalize-space-xpath-function-to-work (also, the
    tag is not "correct" html, since it's an unclosed tag - should be "
    " - which also means it doesn't contain any text)
    – racraman Dec 17 '18 at 04:16
  • 1
    Do you want to *extract text* or *locate by text*? – Andersson Dec 17 '18 at 09:01

3 Answers3

1

Try the below one to get text

String user = driver.findElement(By.xpath("//span[@id='WhoLoggedInUpdatePanel']/h1").getAtrribute("innerText");
miken32
  • 42,008
  • 16
  • 111
  • 154
Akbar
  • 68
  • 1
  • 10
1

Its not good to locate using the name because if login credential get changed then name will be change.

Use //span[@id='WhoLoggedInUpdatePanel']/h1 and grab the text what present under <h1> or equivalent CSS selector span[id='WhoLoggedInUpdatePanel']>h1

String userName = driver.findElement(By.xpath("//span[@id='WhoLoggedInUpdatePanel']/h1")).getText();

and then verify whether your use is expected.

if(userName.contains("Sheikh")){
    System.out.println("valid user");
} else {
    System.out.println("invalid user");
}
NarendraR
  • 7,577
  • 10
  • 44
  • 82
  • Your CSS selector should be `#WhoLoggedInUpdatePanel > h1`. It's simpler, shorter and accomplishes the same thing. – JeffC Dec 17 '18 at 16:33
1

To extract the text Welcome Sheikh, as it is a text node within its ancestor <h1> node, you need to use the method executeScript() and you can use the following solution:

WebElement myElement = driver.findElement(By.xpath("///span[@id='WhoLoggedInUpdatePanel']/h1"));
String myText = ((JavascriptExecutor)driver).executeScript('return arguments[0].lastChild.textContent;', myElement).toString();
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352