Wednesday, December 2, 2015

Facebook and Selenium - Read Messages and Notifications Count

    
Lets continue our experiments on facebook.
We will now see how we can ask our WebDriver to do some social networking stuff on behalf of us.

As a first step, we will get the count of new messages and notifications from our facebook account and print them to your console.

I am writing the direct code below. to understand the context and the link between my code across realated posts, you are requested to read my first post on FB (login)
Here you go ...   http://www.seleniumhq.in/2015/11/facebook-login-using-selenium-webdriver.html




We will initialize our web elements:

    final By MESSAGES_COUNT = By.id("mercurymessagesCountValue");
    final By NOTIFICATIONS_COUNT = By.id("notificationsCountValue");

The method looks something like this

    void printMessageAndNotificationCount()
   {
        String msg_count = "", notification_count = "";
        // We can use wait statements to wait until a first element is visible
        if(isElementFound(MESSAGES_COUNT))
            msg_count = driver.findElement(MESSAGES_COUNT).getText();
        if(isElementFound(NOTIFICATIONS_COUNT))
            notification_count = driver.findElement(NOTIFICATIONS_COUNT).getText();
      
        if(!msg_count.isEmpty())
            System.out.println("YOU HAVE NEW MESSAGES: "+msg_count);
        else
            System.out.println("YOU HAVE NO NEW MESSAGES");  
        if(!notification_count.isEmpty())
            System.out.println("YOU HAVE NEW NOTIFICATIONS: "+notification_count);
        else
            System.out.println("YOU HAVE NO NEW NOTIFICATIONS");  
    }

This will print the results something like this:




Having understood the above code, you might face issues with waiting for some web elements sometimes.
As a beginner, we often end up using "Thread.sleep()" method. We might want to look at my page WebDriver Tips for a custom wait method.



No comments:

Post a Comment