Although a very basic thing, but when I actually started writing the code and made dry runs, I faced two basic challenges: identifying appropriate locators and disabling browser level notifications. But after numerous trials and errors, I was finally able to strike the right chord.
Steps covered:
1. Launch Facebook
2. Login using valid Credentials
3. In the News Feed Section, click on the status text box
4. Write the Status and Post-it
5. Take a Screenshot
6. Logout
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | package com.testersdock.testcase; import java.io.File; import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.apache.commons.io.FileUtils; public class FBLogin { public static void main(String[] args) throws InterruptedException, IOException { //Creating reference of Webdriver Interface WebDriver driver; //Declare Facebook Credentials String user="Enter your Username"; String pass="Enter your Password"; //Creating an instance of chrome level class to disable browser level notifications ChromeOptions coptions = new ChromeOptions(); coptions.addArguments("--disable-notifications"); // Telling Selenium to find Chrome Driver System.setProperty("webdriver.chrome.driver", "/Users/alapan/Desktop/chromedriver"); // Initialize browser driver = new ChromeDriver(coptions); // Launch Facebook driver.get("http://facebook.com/"); //Wait Thread.sleep(1000); //Maximize Window driver.manage().window().maximize(); //Wait Thread.sleep(2000); //Enter Username WebElement userTextField = driver.findElement(By.id("email")); userTextField.sendKeys(user); //Wait Thread.sleep(2000); //Enter Password WebElement PassTextField = driver.findElement(By.id("pass")); PassTextField.sendKeys(pass); //Wait Thread.sleep(2000); //Click on Login button driver.findElement(By.name("login")).click(); //Wait Thread.sleep(10000); //Click on Accept All Cookies button WebElement webElement = driver.findElement(By.cssSelector("div[aria-label="Accept All"]")); webElement.click(); //In case if the browser shows - Click on Not Now for Remember Password button //WebElement element = driver.findElement(By.cssSelector("div[aria-label="Not Now"]:nth-child(2)")); //element.click(); //Click on What's on Your Mind? WebElement TextArea = driver.findElement(By.cssSelector("div[role="button"] > div > span[style*="webkit-box-orient"]")); TextArea.click(); Thread.sleep(3000); //Click on the expanded text area WebElement TextAreaExpanded = driver.findElement(By.cssSelector("div[aria-describedby*="placeholder"]")); TextAreaExpanded.click(); TextAreaExpanded.sendKeys("Hello World"); //Wait Thread.sleep(3000); //Click On Post Button WebElement PostBtn = driver.findElement(By.cssSelector("div[aria-label="Post"]")); PostBtn.click(); //Wait Thread.sleep(4000); // Take Screenshot for Evidence File srce = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); // Save the screenshot in the given path by the name FbStatus.png FileUtils.copyFile(srce, new File("/Users/alapan/Desktop/FbStatus.png")); //Wait Thread.sleep(2000); //Click on Account Settings Dropdown WebElement AccSettings = driver.findElement(By.cssSelector("div[aria-label="Account"]")); AccSettings.click(); //Click on Log out button WebDriverWait wait = new WebDriverWait(driver, 8); WebElement logout = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("i.hu5pjgll.lzf7d6o1.sp_09gpAzWhK7K.sx_2eadd2"))); logout.click(); //Wait Thread.sleep(2000); // Close the browser driver.quit(); } } |
Update:
1. The web notifications were not getting disabled for Firefox. To do, that replace:
1 2 3 | //Creating an instance of chrome level class to disable browser level notifications ChromeOptions coptions = new ChromeOptions(); coptions.addArguments("--disable-notifications"); |
With:
1 2 3 4 5 6 7 | //Disable Browser Notifications for Firefox FirefoxProfile newProfile = new FirefoxProfile(); newProfile.setPreference("dom.webnotifications.enabled", false); DesiredCapabilities desCap = DesiredCapabilities.firefox(); desCap.setCapability(FirefoxDriver.PROFILE, newProfile); FirefoxOptions opt = new FirefoxOptions(); opt.merge(desCap); |
2. Updated the locators for the Login button, Status Text Box, Post button, Account settings, and Logout button. Added the button click for Accept All cookies.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //Click on Login button driver.findElement(By.name("login")).click(); //Click on Accept All Cookies button WebElement webElement = driver.findElement(By.cssSelector("div[aria-label="Accept All"]")); webElement.click(); //Click on What's on Your Mind? WebElement TextArea = driver.findElement(By.cssSelector("div[role="button"] > div > span[style*="webkit-box-orient"]")); TextArea.click(); Thread.sleep(3000); //Click on the expanded text area WebElement TextAreaExpanded = driver.findElement(By.cssSelector("div[aria-describedby*="placeholder"]")); TextAreaExpanded.click(); TextAreaExpanded.sendKeys("Hello World"); //Click On Post Button WebElement PostBtn = driver.findElement(By.cssSelector("div[aria-label="Post"]")); PostBtn.click(); //Click on Account Settings Dropdown WebElement AccSettings = driver.findElement(By.cssSelector("div[aria-label="Account"]")); AccSettings.click(); //Click on Log out button WebDriverWait wait = new WebDriverWait(driver, 8); WebElement logout = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("i.hu5pjgll.lzf7d6o1.sp_09gpAzWhK7K.sx_2eadd2"))); logout.click(); |
This does not work. It gives a stale element exception.
Thanks for the comment Aishvarya. I wrote this script a few months back and since then there have been some changes in Facebook UI. So following your comment, when I debugged the script I found the issue as:
Caused by: org.openqa.selenium.NoSuchElementException:
Cannot locate an element using By.linkText: Log out
Turns out that Selenium was not able to find the Log out button. So when I checked the Facebook UI the previous Log out was changed to Log Out (O in caps). I have made the changes, and now the script runs fine.
Can you post your code here.
It is very hard to tell from just one block of code. Would be great if you can share the entire code.
Hi,
I am working with virtual client (Centos)
and faced following issue:
Successfully wrote the post message , but message window not opening
as a result “Post” button isn’t visible
This occurs only if run automation when virtual machine console is closed.
Hi Alapan, Code is working on Chrome browser but not on Firefox (Unable to type the text in status). Could you please help?
Hi Venkat, I have updated the main post with the changes required to run the script on Firefox. Let me know if you face any issues.
Hey, I like your code, would like to connect with you! please email me!
Best,
SAQIB
Make a more new posts please 🙂
Hi , I am facing an issue for the Share button. The path is not being located by the driver. can you help?
Hi Prachi. Can you share the code snippet that you’re working on?
Hi,
I am not able to run the script as i unable to find the element “xhpc_message” i have checked the HTML there is no such element. Could you please help me in resolving this
Hey Akash! Go to Facebook Page Source (Right Click -> View Page Source) and search for ‘xhpc_message’. You will find it as the name for the facebook status box (text area), which we are using in our code. Look into the image for more clarity:
Hi Alapan, can you share your email id so that I can reach out for discussing some work-related things?
Hi Alapan,
I think the UI has changed, xhpc_message isnt available. Any help here?
Go to Facebook Page Source (Right Click -> View Page Source) and search for ?xhpc_message?. You will find it as the name for the facebook status box (text area), which we are using in our code. Look into the image for more clarity:
Hi,
i am unable to write the code for search text box in facebook home page after we login , please help
Can you give this locator a try and let me know if it works: input[data-testid=”search_input”]
Hi Alpan,
I’ve gone thru your posts and are pretty much helpful and thanks for the wonderful posts.
I was trying to automate the Facebook Clear Search functionality, almost done with this but the last step keeps on failing like unable to click on the Clear Searches button on the pop up as the xpath id is changing for every run so this is why i’m unable to click on the button in the pop up. Can you please help me out in how to handle the xpath id’s while changing on the run
Hi
I am unable to post status in fb, xhpc_message object does not seem to work now please help
What is the error that you’re getting?
Exception in thread “main” org.openqa.selenium.NoSuchElementException: Unable to locate element: *[name=’xhpc_message’]
I have updated the script with new locators. Please Do check out.
Thank you for the information! I use a browser extension called cucomm. The program automatically sends messages to users on Facebook and doesn’t require a password from your account. It is convenient and saves time, I advise you to try it.
Hi,
I think for the new UI of Facebook its not working:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {“method”:”css selector”,”selector”:”div[aria-label=”Account”]”}
(Session info: chrome=107.0.5304.107)
Can you please help me in this.
worked when i have used: driver.findElement(By.className(“x3ajldb”))