I'm using StringUtils from the Apache commons library to check the # of matches of a sub-string within the source code of an HTML page.

I have converted the page source using the WebDriver command:

String pageSource = driver.getPageSource();    

The code I'm using to find # of matches is:

int cloudfCount = StringUtils.countMatches(pageSource, "cloudfront");
System.out.println("There are " + cloudfCount + " instances of cloudf text found within the page source.");

When I right-click within the page, view source, then Ctrl-F to find CloudFront, I get 2 matches. Which is what I'm expecting.

But when I use the above code in an automated Selenium script, I'm getting 5 results.

Any thoughts/ideas on where I'm going wrong?

Could it somehow be related to the fact, that the CloudFront text is part of 2 JavaScript tags within the page source?

  • Do a ctrl + f on the page source given by webdriver and the one in your browser. See the difference. Apr 20, 2015 at 10:14

3 Answers 3


You are comparing apples and oranges. Selenium works off the DOM, not off the page source. For a more fair comparison, try opening the browser debugger and searching for "cloud front".


This is very much possible.

When you try to find a text in the web page displayed within a browser, only the actual content of the web page is showed. The browser doesn't show the complete HTML source or DOM.

So when you do CTRL+F in a browser and look up "cloudfront" it would return 1 if the text is displayed only once in the content.

But, if you look it up within your browser's console, you would notice the text "cloudfront" may be mentioned within any scripts and external sources being called with in the HTML DOM. Try to check the <head> section for links and scripts being called. Also check the <script> tags within the HTML source. Such links and scripts do not display within the page in the browser. they work in the back to make the content presentable in the browser's display area.


I would do something like:


Then I would get the size of the variable where I store the result of the above statement and compare it vs. my expected count.

(excuse the casing if its incorrect in the code)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.