Roy Roy - 2 years ago 189
Java Question

Printing desired text using selenium webdriver

Below is the HTML Query.

<div id="dvCount" style="">
<span>Total Log Count : </span>
<span id="spnLogCount">46</span>

I want to print the value
in Selenium Webdriver. please let me know the code.

Code currently i am using but unable to get the value

WebElemet Text= driver.Findelement(By.cssselector(xpath).gettext();
system.out.println("total" + Text);

But this code is not working. How do I properly get to the value in tje "spnLogCount" tag?

Answer Source
public static void main(String[] args) {
        // TODO Auto-generated method stub

        WebDriver driver = new FirefoxDriver();

        // way one
        // you can create your custom x path
        // one x path can be made directly using id of the span like 
        // xpath =  //span[@id='spnLogCount']
        // also not if you are not sure of the tag name then you can also use * in xpath like below
        String myText = driver.findElement(By.xpath("//*[@id='dvCount']/span[2]")).getText();
        System.out.println("Total Log Count :  " + myText);

        // way two
        // you can directly use id 
        myText = driver.findElement("spnLogCount")).getText();
        System.out.println("Total Log Count :  " + myText);

        // way three
        // if you are using css selector then for id you can use #
        myText = driver.findElement(By.cssSelector("#spnLogCount")).getText();
        System.out.println("Total Log Count :  " + myText);



             driver.findElement(By.linkText("Info Log")).click();

             driver.findElement("txtMessage")).sendKeys("Push Success");




            // use it just before the sendkeys code like this 
            String text = driver.findElement(By.xpath("//*[@id='dvCount']/span[2]")).getText();
Hope this helps 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download