Search code examples
javaselenium-chromedriverautotest

FInd element on page


I have a this page,

On page is elements share (left-down on post):

<button class="btn btn_share" role="dropdown_trigger" data-toggle="dropdown" type="button" title=" Поделиться вопросом" aria-expanded="false">
  <svg class="icon_svg icon_sharing" viewBox="0 0 32 32">
    <use href="5e6a141a/images/sprite.svg#icon_sharing"></use>
  </svg>
</button>

Tried using [tags:xpath],

List<WebElement> elements=driver.findElements(By.xpath("xpath=//div[@class='btn btn_share']/div/div[5]/div/button"));

if (elements == null) {
    System.out.println("sharing no found");
    System.exit(1);
} else {
    for (WebElement element : elements) {
        element.click();
    }
}

and using class select.

List<WebElement> elements=driver.findElementsByClassName("btn_share");

if (elements == null) {
    System.out.println("sharing no found");
    System.exit(1);
} else {
    for (WebElement element : elements) {
        element.click();
        TimeUnit.SECONDS.sleep(50);
    }
}

But no any result.

How can I select one element and click?


Solution

  • Use find elements By.cssSelector with this value : [class*='btn_share'].

    And for the validation you can use elements.size()==0 not elements == null.

    List<WebElement> elements = driver.findElements(By.cssSelector("[class*='btn_share']"));
    
    if(elements.size()==0) {
        System.out.println("sharing no found");
    }else {
        for(WebElement element: elements) {
            element.click();
        }
    }
    

    CSS Selector Reference