Auto Login to Facebook with Selenium

Once you have logged in to Facebook you stay logged in till you do a logout. This means you can close Facebook and when you come back you are automatically logged in. This works because Facebook stores a Cooky on your device containing your login information.

In this blog post I show you how you can achieve this behavior using Selenium and MyITest4U.

The steps to auto login are:

  • Make a test which logs in to Facebook.
  • Store the cookies into a file.
  • Make a test which will open Facebook and read the cookies from the stored file.

Below is a step by step guide of how to achieve the above three steps.

  1. Create an AUT in MyITest4U with Root URL and Page URL https://www.facebook.com.
  2. Create a test block with the only step Sleep for 5 seconds and the checkbox Collect after Step selected. Sleeping for 5 seconds should be enough for the cookies overlay to appear.
    Run the Sleep test block.
  3. Create a test block which clicks the Allow all cookies button.
    Do a GUI element search with element set to Allow all cookies.
    The search should result in one hit. After selecting this hit click on Add Test Step and finish the test block. Once again select the checkbox Collect after Step and run the test block.
  4. Generate the Login test block by selecting the Make All Forms from the Generator menu. Select both checkboxes in the Prepend Test Name dialog.
  5. Create a test block with the single step Write Cookies. URL, Tag and Element are all set to NoGuiElement.
  6. Create a test with the following test blocks:
    • AllowAllCookies
    • BFTprivacymutationtokeneyJ0eXBlIjowLCJjcmVhdGlvbl90aW1lIjoxNjg0OTk1NzE1
    • SaveCookies
    l_loginFacebook
    Set email and pass and run the test.
  7. Create a test block doing the auto login. The test block has the following test steps:
    • Sleep
    • SetCookies
    • BrowserRefresh
    URL, Tag and Element are set to NoGuiElement in the three test steps. Select Take Screenshot that you can see if the auto login worked and Collect after Step that you can continue writing further tests.

MyITest4U stores the cookies set by Facebook in the file cookies.txt in step 6. The cookies.txt is read in step 7 to do the auto login.

The setting of the cookies can be used generally to deal with the cookies message which appears on almost every page. It works the following way:

  • create a test accepting the cookies to store the cookies in a file
  • create the test described in step 7

The domain for storing and setting the cookies has to be the same. Otherwise it might not work.