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")
);