Selenium For Beginners

Share this post

User's avatar
Selenium For Beginners
How to create a custom expected condition
Waits

How to create a custom expected condition

Alex Siminiuc's avatar
Alex Siminiuc
Jun 14, 2023
∙ Paid

Share this post

User's avatar
Selenium For Beginners
How to create a custom expected condition
Share

We have seen in a previous post that the Selenium library offers out-of-the-box many expected conditions. Some of these are related to the page url and title and allow waiting until the url/title is equal to a value or contains one.

But what if we need an expected condition that requires a different type of validation for the page url?

Let’s say that we want to wait until the page url is available and is valid as a url (starts with a protocol, followed by :, followed by the domain name, etc).

How do we do this?


The code that checks for the validity of the page url is simple:

String regex = 
    "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";

String url = driver.getCurrentUrl();

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(url);

boolean isValid = matcher.matches();

The code needs a regular expression value for a valid url so it uses the regex variable for it. Then, it gets the current url using driver.getCurrentUrl(). It compiles a pattern using the regular expression. It creates a matcher from the pattern and the url. Finally, it checks if the matcher matches, meaning, if the url matches the regular expression.

How do we use this code to create a custom expected condition?

Keep reading with a 7-day free trial

Subscribe to Selenium For Beginners to keep reading this post and get 7 days of free access to the full post archives.

Already a paid subscriber? Sign in
© 2025 Alex Siminiuc
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share