简体   繁体   中英

How to verify links and click on them in Selenium webdriver Java

I am new in selenium. I have similar links on the page with similar xpaths (let's say links 1 to 30). I need to verify that all of them are present on the page (I want selenium to print something like this "element 1 is present" for each element) and all of them are clickable(new page will opens). So far I have this code to click on all links one by one and print their titles:

    driver.get("http://anysite.com");
    String part1=".//*[@id='footer']/div/div[1]/div[2]/ul/li[";
    String part2="]/a";
    for (int i=1;i<=30;i++){
    String text = driver.findElement(By.xpath(part1+i+part2)).getText();
    System.out.println(text);
    driver.findElement(By.xpath(part1+i+part2)).click();
    System.out.println(driver.getTitle());
    driver.get("http://anysite.com");

Also I have this code to verify presence of each individual link separately (if I have 30 links I have to duplicate this code 30 times):

    if(driver.findElements(By.xpath(".//*[@id='footer']/div/div[1]/div[2]/ul/li[1]/a")).size() != 0){
      System.out.println("Element Link 1 is Present");
      }else{
      System.out.println("Element Link 1 is Absent");
      }

So far I have two test cases, is there is any way to combine this two pieces together in one nice piece? Thank you!

In String 1 you are taking xpath as:

String part1=".//*[@id='footer']/div/div[1]/div[2]/ul/li[";

while it should be:

String part1="//*[@id='footer']/div/div[1]/div[2]/ul/li[";

You need to remove dot "." from your xpath.

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