Search code examples
javaselenium-webdriverautomated-tests

how to get value using css for locators in selenium java


We have a application where most of the elements are having labels and corresponding input/element, we want to fetch value from each field or sometimes based on the label name we want to enter values

ex:

<div class="ant-row"><div class="ant-col ant-col-10"><b>UserName.</b>:</div><div class="ant-col ant-col-14"> Tiger</div></div>
<div class="ant-row"><div class="ant-col ant-col-10"><b>UserType.</b>:</div><div class="ant-col ant-col-14"> Animal</div></div>

How do I get value of UserName. , UserType., here I don't want to use class since they are dynamic. I want to fetch based on text like UserType.

Its preferable CSS locator for selenium java , we are following page factory model.


Solution

  • Refer the below XPath expression:

    //b[text()='UserName.']//following::div[1]
    

    and

    //b[text()='UserType.']//following::div[1]
    

    Explanation:

    • //b[text()='UserName.'] -- This part will locate <b> node that contains the text value UserName.
    • //following::div[1] -- This part uses the following axis to select the first <div> element that comes after the previously selected <b> element

    Java Code:

    System.out.println(driver.findElement(By.xpath("//b[text()='UserName.']//following::div[1]")).getText());
    System.out.println(driver.findElement(By.xpath("//b[text()='UserType.']//following::div[1]")).getText());
    

    Should output:

    Tiger
    Animal