Roy Roy - 7 months ago 10
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>
</div>


I want to print the value
46
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
public static void main(String[] args) {
        // TODO Auto-generated method stub

        WebDriver driver = new FirefoxDriver();
        driver.get("file:///C:/Users/rajnish/Desktop/my.html");

        // 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(By.id("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);

    }

UPDATE

 driver.findElement(By.id("ui-id-3")).click();
             driver.findElement(By.linkText("Info Log")).click();

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

             driver.findElement(By.id("txtMachineName")).sendKeys("AC204");

             driver.findElement(By.id("txtPortal")).sendKeys("91");

             driver.findElement(By.id("btnSearch")).click();

            // use it just before the sendkeys code like this 
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='dvCount']/span[2]")));
            String text = driver.findElement(By.xpath("//*[@id='dvCount']/span[2]")).getText();
            System.out.println(text);
Hope this helps