简体   繁体   中英

Selenium Webdriver, how to validate a string in a url

Any help to validate a parameter in the url using selenium web driver + java

getCurrentUrl() = https://www.loca.com/usa/test/#/xxx

My url string is as above, and based on the url I need to enter a value on the loaded page, like lets say - I have zipcode field to enter zipcode value.

If url string contains 'usa' Enter zipcode as 12345 if url string contains canada Enter zipcode as Ab1233

If you are using Java, you can do something like:

String zipcode = "";
String currentUrl = "https://www.loca.com/usa/test/#/xxx"
//This will check to make sure USA is a part of the URL, and doesn't exist as another part of the URL.
if(currentUrl.contains("/usa/")){
   zipcode = "12345";
//Same here with Canada
} else if(currentUrl.contains("/canada/"){
   zipcode = "ab1233"; 
//You can continue pattern for any other countries
} else if(currentUrl.contains(...){
...

Just put the URL into a string, and then use the String method contains to check and see if USA in the string. If it is, use zip code, otherwise, do something else.

I think an if then else is going to get pretty messy if you have more than just a few of them. I prefer to use a switch . I think it makes the code easier to read but maybe that's a personal preference.

String currentUrl = "https://www.loca.com/usa/test/#/xxx";
String patternString1 = ".com\\/(\\w+)\\/";
Matcher matcher = Pattern.compile(patternString1).matcher(currentUrl);
if (matcher.find())
{
    String zipcode = "";
    switch (matcher.group(1))
    {
        case "usa":
            zipcode = "12345";
            break;
        case "canada":
            zipcode = "Ab1233";
            break;
        default:
            // handle an unexpected country
            break;
    }
}
else
{
    // handle the case of a bad URL
}

// do something with zipcode
System.out.println(zipcode);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM