简体   繁体   English

如何检查网址中的搜索关键字

[英]How do I Check search keyword in the URL

I am a beginner in Selenium. 我是硒的初学者。 I wanted to know how I can verify the URL against the keyword I entered in the search bar. 我想知道如何根据在搜索栏中输入的关键字来验证网址。

The search page url is https://catalog-mytest.com/search? 搜索页面网址是https://catalog-mytest.com/search?

When I entered redcar in the search bar and hit enter, the url becomes https://catalog-mytest.com/search?keywords=redcar 当我在搜索栏中输入redcar并按Enter键时,该URL变为https://catalog-mytest.com/search?keywords=redcar

Could you guide me on how to write a piece of code that would verify the URL with the keywords? 您能否指导我如何编写一段代码来验证带有关键字的URL? thank you. 谢谢。

There can be two approaches- 可以有两种方法-

Approach-1: 方法1:

String url = Driver.getCurrentUrl();
boolean passed = url.contains("your keyword here");
if (passed) {
    System.out.println("Test Passed");
} else {
    System.out.println("Test Failed");
    Assert.fail("This message will be printed in stacktrace if the assertion fails.");
}

This is the simplest way of doing this. 这是最简单的方法。

Approach-2: 方法2:

String keyword = Driver.getCurrentUrl().split("?")[1].split("=")[1];
boolean passed = keyword.equals("your keyword here");
if (passed) {
    System.out.println("Test Passed");
} else {
    System.out.println("Test Failed");
    Assert.fail("This message will be printed in stacktrace if the assertion fails.");
}

This approach can be error prone, if the URL does not always contain ? 如果URL并不总是包含? ,则此方法容易出错? , = in it then the test can fail with ArrayIndexOutOfBoundsException =在其中,则测试可能因ArrayIndexOutOfBoundsException失败

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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