Python code to Automate Facebook Login

7149

Table of Contents

Python code to login to Facebook.

To implement this code we will need to import webdriver from the Selenium library, for Python. We will set-up a Firefox driver using Selenium. We need to access the login URL page for Facebook. After that, we need to access XPATH for Facebook such as: username, password form field, and a login button. Finally, we will send a post request by clicking the login button. It is one of the simplest ways to login without using API. Instead of using the requests library, we chose to use Selenium because it makes a job lot easier, as we do not need to set additional parameters.

Python code implementation to login to Facebook using Selenium.

 

Code:

 

from selenium import webdriver
driver = webdriver.Firefox(executable_path=r'C:\driver\geckodriver.exe')
driver.get('https://facebook.com')
driver.maximize_window()
driver.find_element_by_xpath('//*[@id="email"]').send_keys('username')
driver.find_element_by_xpath('//*[@id="pass"]').send_keys('passwd')
driver.find_element_by_xpath('//*[@id="loginbutton"]').click()

 

 

Steps required to login to Facebook Page using Python

  • Setting up Firefox driver using Selenium
  • Carefully set the Fullpath name, where the geckodriver.exe file is placed.
  • The login page URL (such as https://facebook.com) – GET Request operation
  •  XPATH for username – Send_Keys (it can also be CSS selector, class name or tag instead of XPATH): //*[@id=”email”]
  • XPATH for the password – Send_Keys operation : //*[@id=”pass”]
  •  XPATH for the login button. – click() : //*[@id=”loginbutton”]
  • Then sending a post request by clicking login button.