πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 66 of 100
Element Interaction
Beginner

Verifying Text Presence Globally on a Page

πŸ“Scenario Overview

Verifying Text Presence Globally on a Page

Key Takeaways & Cheat Sheet

  • βœ“Target the body container tag using text-content lookups
  • βœ“Use contains() or matches() assertions to find matching strings
  • βœ“Wait explicitly for the global text to appear in DOM
  • βœ“Limit global string searches to prevent false positives

Short Direct Answer

To verify text presence, query the page `body` element using `driver.findElement(By.tagName("body")).getText()`. This retrieves only visible, rendered text, avoiding the risk of false positives from hidden scripts or raw HTML.

⚠️ Senior Warning (Red Flag)

Never use driver.getPageSource().contains("text") as your primary text validation strategy. Page source contains raw HTML, script blocks, and metadata, which can lead to false positives on matches inside script code.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Targeting specific containers with textToBePresentInElementLocated is highly recommended. It isolates your assertion to the target area, avoiding false positives.

SeleniumAutomation.java
Selenium 4 + Java
// ❌ Fragile check: returns true even if text is hidden inside a script tag
// boolean match = driver.getPageSource().contains("Payment Successful");

// βœ… Best Practice: Check visible text inside the page body
WebElement body = driver.findElement(By.tagName("body"));
String visibleText = body.getText();
assert visibleText.contains("Payment Successful");

// βœ… Alternative: Wait explicitly for text to render inside a specific container
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
boolean textPresent = wait.until(
    ExpectedConditions.textToBePresentInElementLocated(By.id("status-box"), "Payment Successful")
);