The Wayback Machine - https://web.archive.org/web/20240930224747/https://www.geeksforgeeks.org/bulk-posting-on-facebook-pages-using-selenium/
Open In App

Bulk Posting on Facebook Pages using Selenium

Last Updated : 08 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

As we are aware that there are multiple tasks in the marketing agencies which are happening manually, and one of those tasks is bulk posting on several Facebook pages, which is very time-consuming and sometimes very tedious to do. In this project-based article, we are going to explore a solution that is on the python selenium library and see how we can use it & implement this to use it in our daily life.

Requirement:

  • Python selenium library (This library is like API to access the selenium web driver to control Chrome, Firefox, etc.)
  • Chromium Web drivers (To use & Control Chrome browser, this driver requires to be present in your system)

Installations:

  • To install selenium.
pip install selenium
  • For web driver, you need to download the chromedriver.exe file and need to put it in the same folder where you have extracted this project. If you are using another browser other than Chrome (eg: Firefox) download search <your browser name> webdriver and do the same exercise.

Note: Also provided the chromedriver.exe with the project. But it is better to download the latest driver from the official website to avoid the version issues.

Let’s explore the project files:

  • PostingContents.txt: In this file, We need to give content that we want to publish on Facebook Pages.
  • credentials_load.json: In this JSON file, we need to give these details:
    • In the “Page Names” field, you need to give your Facebook Page names where we want to publish the content. Page names should come between double-string quotes. For example, I have added some of my Facebook page names, and replace them with your pages.
    • In the “Email Address” field, you need to give your Facebook login email address, and this information is only to log in to Facebook.
    • In the “Password” field, you need to give your Facebook password to log in. This information is only to log in to Facebook.

credentials_load.json

How does it work?

For bulk posting, the script does a couple of things:

  • Loads credentials_loads.json and posts the content file to use it for login and posting purposes
  • Open the Chrome browser and loads the Facebook login Page.
  • Once the Login page is loaded, it automatically fills the login email address and password (will take from credentials_loads.json file).
  • After that script pauses and tells the user to perform actions like Permit the login if 2FA enable after that, show notification box appears (click on the block option)
  • After completing those tasks, type “y” in the cmd (where the script is running) and click ENTER so that script can start running.
  • Now, the script loads the Facebook pages list and open the given page (mentioned pages in the credentials_loads.json file) one by one and posts the content. In each posting, the script pauses for some seconds so that elements can load completely. Otherwise, it will raise some errors.
  • After completing posting works, the script will automatically log out and close the chrome.

Below is the implementation:

Python3




# Social Bot Version 1 Codes:
 
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import json
import os
 
 
class Social_bot:
    def __init__(self):
 
        # instance/class variables
        # Facebook page url
        self.login_page = "https://www.facebook.com/"
 
        # Facebook Page Menu Url
 
        # Chrome Driver path, Important
        self.chromium_path = os.path.abspath("chromedriver.exe")
 
        # By default session is None,
        # will set after Starting the chrome
        self.browser_session = None
 
        # By default is set to 0,
        # if any website visits then
        # will be increment by one, only set to integer
        self.browser_visit = 0
 
        # By default is set to 0,
        # which represents no login
        self.login = 0
 
        # By default is set to 5,
        # will be used by time patterns
        self.time_pattern = 5  # seconds
 
        # Xpath For Facebook login id - email
        self.user_xpath = "//input[@id='email']"
 
        # Xpath for Facebook login password
        self.pass_xpath = "//input[@id='pass']"
 
        # For facebook login id credentials
        self.user = None
 
        # For Facebook login password credentials
        self.password = None
 
        # Xpath for facebook logout
        self.logout_fb = ["/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[4]/div[1]/span[1]/div[1]/div[1]/i[1]",
                          "/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[4]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[5]/div[1]/div[1]/div[2]/div[1]",
                          "//div[@class='oajrlxb2 s1i5eluu gcieejh5 bn081pho humdl8nn izx4hr6d rq0escxv nhd2j8a9 j83agx80 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys d1544ag0 qt6c0cv9 tw6a2znq i1ao9s8h esuyzwwr f1sip0of lzcic4wl l9j0dhe7 abiwlrkh p8dawk7l beltcj47 p86d2i9g aot14ch1 kzx2olss cbu4d94t taijpn5t ni8dbmo4 stjgntxs k4urcfbm tv7at329']//div[@class='rq0escxv l9j0dhe7 du4w35lb j83agx80 pfnyh3mw taijpn5t bp9cbjyn owycx6da btwxx1t3 c4xchbtz by2jbhx6']"]
 
        # Page Name list
        self.fb_page_partial = None
 
        # Xpath for Facebook posting
        self.fb_posting = ["/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[4]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]",
                           "/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]",
                           "/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[2]/div[3]/div[4]/div[1]"]
 
        # Text posting content variable
        # Will be set via text_posting_content_load function
        # By default set to None
        self.textContents = None
 
    def initiate_chrome(self):
        # This function is to start chrome
        # Successful login will return 1
 
        if self.browser_session == None:
            self.browser_session = webdriver.Chrome(self.chromium_path)
            return 1
        else:
            return -1
 
    def close_session(self):
        # This function is to close the session
        # Successful operation will return 1
 
        if self.browser_session == None:
            return
        else:
            self.browser_session.close()
            self.browser_session.quit()
            self.browser_session = None
            return 1
 
    def page_load(self, path=None):
        # This function is to load page,
        # successful operation will return None
 
        if path == None:
 
            # if no url given, then it will return -1
            if self.browser_session == None:
                return -1
            else:
                self.browser_session.get(self.login_page)
                self.browser_visit += 1
        else:
 
            # if session is not created, then will return -1
            if self.browser_session == None:
                return -1
            else:
 
                # Successful operation will also
                # add one in instance variable to
                # track number of visited pages
                self.browser_session.get(path)
                self.browser_visit += 1
 
    def reverse_visit(self, back_v=None):
 
        # This function is to go back to previous page
        # This function takes argument back_v for
        # telling function to back number of pages
        # If no value pass for back_v then it will go back to main page(starting page).
 
        if self.browser_visit == None:
 
            # if self.browser_visit instance
            # variable is None, then it will return -1
            return -1
        else:
 
            # if back_v is not given,
            # then with help of loop will go back
            # also set the browser_visit to 0
            if back_v == None:
                for vp in range(self.browser_visit):
                    self.browser_session.back()
                self.browser_visit = 0
                return 1
            else:
 
                # if back_v is given, then go back with the help of loop
                for vp in range(back_v):
                    self.browser_session.back()
                    self.browser_visit - = vp
                return 1
 
    def do_login(self, user_name=None, user_pass=None):
 
        # This function is to do login on social media,
        # takes two arguments user name and password
        # By default these argument set to None, and in no use
 
        if self.browser_session == None or self.login == 1:
 
            # if self.browser not started,
            # or already login happened then it will return -1
            return -1
 
        elif user_name != None or user_pass != None:
            return -1
 
        else:
 
            # Successful operations will use xpath,
            # and login to use the site
            # self.browser_visit will increment by 1
            # self.login will be set to 1 for successful login
 
            self.browser_session.find_element_by_xpath(
                self.user_xpath).send_keys(self.user)
            self.browser_session.find_element_by_xpath(
                self.pass_xpath).send_keys(self.password, Keys.ENTER)
            self.browser_visit += 1
            self.login = 1
            return 1
 
    def do_logout(self):
 
        # This function is to use
        # log out the social media
        if self.browser_session == None or self.login == 0:
 
            # if no session available or
            # login then it will return -1
            return -1
 
        else:
 
            # To logout the site via xpath,
            # and also follow time_patterns()
            # function to pause the
            # script for sometime.
            # Important bcz sometimes some xpath are not loaded,
            # and take time to load, so this function is important
            # Failed operation will return -1, and successful will return 1
            try:
 
                self.browser_session.find_element_by_xpath(
                    self.logout_fb[0]).click()
 
                self.time_patterns()
 
                self.browser_session.find_element_by_xpath(
                    self.logout_fb[1]).click()
 
                self.time_patterns()
 
                self.browser_session.find_element_by_xpath(
                    self.logout_fb[2]).click()
                return 1
            except:
                return -1
 
    def time_patterns(self, tp=None):
 
        # This function is to pause the script for sometime
        # Also takes argument as second,
        # if not given then it will
        # take by default seconds to wait
        # Successful operation will return 1
 
        if tp == None:
            time.sleep(self.time_pattern)
            return 1
        else:
            self.time_pattern = tp
            time.sleep(self.time_pattern)
            return 1
 
    def page_navigation_partial(self, pg_name):
 
        # This function is use to load only specified page,
        # need to given page name
        # for navigating the page
 
        if self.browser_session == None:
 
            # if no browser session
            # available then it will return -1
            return -1
        else:
 
            # it will return find specified text partially
            # successful operation will also
            # increment the browser_visit by one
 
            self.browser_session.
            find_element_by_partial_link_text(pg_name).click()
 
            self.browser_visit += 1
 
    def page_posting(self):
 
        # This function is to do posting on website
        # Takes argument for posting text
        # Successful operation will return 1
 
        if self.browser_session == None:
 
            # if no browser_session
            # started then it will return -1
            return -1
 
        else:
 
            # These operations will be followed
            # by time patterns function,
            # and in the end also
            # use reverse_visit to reverse the page by one
 
            self.browser_session.find_element_by_xpath(
                self.fb_posting[0]).click()
 
            self.time_patterns()
            self.browser_session.find_element_by_xpath(
                self.fb_posting[1]).send_keys(
                Keys.ENTER, self.textContents)
 
            self.time_patterns()
 
            self.browser_session.find_element_by_xpath(
                self.fb_posting[2]).click()
 
            self.time_patterns()
            self.reverse_visit(1)
            self.time_patterns()
            return 1
 
    def credential_loads_using_json(self):
 
        # This function is to load
        # credentials from json file
        # Will help to set credentials
        # instead of manual
        try:
            with open("credentials_load.json") as filePointer:
                contents = filePointer.read()
 
            contents = json.loads(contents)
 
            self.fb_page_partial = contents["Page Names"]
            self.user = contents["Email Address"]
            self.password = contents["Password"]
 
            # for freeing the json memory part
            del(contents)
            return 1
        except:
            return -1
 
    def text_posting_content_load(self):
        try:
            with open("PostingContents.txt", "r") as filePointer:
                textContents = filePointer.read()
 
            self.textContents = textContents
            return 1
        except:
            return -1
 
 
def soc_bot():
 
    # Creating an Instance of Social bot object
    bot = Social_bot()
 
    # Calling the initiate
    # chrome method to start the chrome
    bot.initiate_chrome()
 
    # For loading credentials and other things
    bot.credential_loads_using_json()
 
    # For loading text based posting content
    bot.text_posting_content_load()
 
    # for loading the facebook
    bot.page_load()
 
    # for login the website
    bot.do_login()
 
    ask_to_block_notif = input(
        "[+] Perform these tasks:\n1.Accept the 2FA if required to do \n2. Once FB Page Load, Please Block the Show Notification Dialog box. Once done, Please press to start the posting Script(Y/N) > ")
 
    # Below statement will pause the script
    # until you clear the above given instructions
    if ask_to_block_notif.upper() == "Y":
 
        # will load the specified page
        bot.page_load(bot.page_ref)
 
        # for pausing the script for sometime
        bot.time_patterns()
 
        # Iterate through Page Names
        for link in bot.fb_page_partial:
 
            # load given facebook page by their name
            bot.page_navigation_partial(link)
 
            # pause the script for sometime
            bot.time_patterns()
 
            # for posting the text based content
            bot.page_posting()
 
            # Print Page Name on Screen
            print("[+] Posting Done on {}".format(link))
 
        # for logging out the facebook
        bot.do_logout()
 
        # for closing chrome & session
        bot.close_session()
        print("[+] Posting Work Done!")
 
        # return 1 for successful operation
        return 1
    else:
        bot.close_session()
        return -1
 
 
if __name__ == "__main__":
    print("SOCIAL BOT SCRIPT INITIATED")
    soc_bot()


Output:

 

 



Previous Article
Next Article

Similar Reads

How to scrape multiple pages using Selenium in Python?
As we know, selenium is a web-based automation tool that helps us to automate browsers. Selenium is an Open-Source testing tool which means we can easily download it from the internet and use it. With the help of Selenium, we can also scrap the data from the webpages. Here, In this article, we are going to discuss how to scrap multiple pages using
4 min read
Bulk update of rows in Postgres DB using psycopg2
PostgreSQL or Postgres is an open-source, relational, SQL complaint, database management system. It allows, the developers, to create complex applications, supporting SQL and JSON querying. It safely stores, and, scales workloads. Psycopg2 is a driver, that is used, for interacting, with Postgres data, using the Python scripting language. It is, us
6 min read
Bulk Insert to Pandas DataFrame Using SQLAlchemy - Python
Let's start with SQLAlchemy, a Python library that allows communication with databases(MySQL, PostgreSQL etc.) and Python. This library is used as an Object Relational Mapper tool that translates Python classes to tables in relational databases and automatically converts function calls to SQL statements that gives application developers the full po
3 min read
Bulk insert with SQLAlchemy ORM in Python
In this article, we will see how to insert or add bulk data using SQLAlchemy in Python. SQLAlchemy is among one of the best libraries to establish communication between python and databases. We have used the PostgreSQL database for this article. Create a database for demonstration: CREATE DATABASE TEST; Create a connection to the Postgres database
1 min read
Build a Bulk File Rename Tool With Python and PyQt
In this tutorial, we will learn how to create a file renaming tool using Python and PyQt5. PyQt5 is a set of Python bindings for the cross-platform application framework Qt, which is used to create graphical user interfaces (GUIs). We will use the OS module to interact with the file system, and the QFileDialog and QMessageBox classes from PyQt5 to
6 min read
SQLalchemy Bulk insert with one to one relation
When working with databases in Python, SQLAlchemy is a popular and powerful library that provides a high-level interface for interacting with relational databases. It offers an Object-Relational Mapping (ORM) layer that allows developers to work with database tables as Python objects. In this article, we will explore how to perform bulk inserts wit
5 min read
How to Create Dynamic Web Pages using Apache Velocity?
Apache Velocity is an open-source java-based templating engine that can play as an alternative to JSP (Jakarta server pages). It is helpful to generate XML files, SQL, etc., In this article, let us see the creation of dynamic web pages. Working way of Velocity: Velocity engine initializationReading the templatePutting the data model in the context
6 min read
How to Scrape Multiple Pages of a Website Using Python?
Web Scraping is a method of extracting useful data from a website using computer programs without having to manually do it. This data can then be exported and categorically organized for various purposes. Some common places where Web Scraping finds its use are Market research & Analysis Websites, Price Comparison Tools, Search Engines, Data Col
6 min read
How to Extract Script and CSS Files from Web Pages in Python ?
Prerequisite: RequestsBeautifulSoupFile Handling in Python In this article, we will discuss how to extract Script and CSS Files from Web Pages using Python. For this, we will be downloading the CSS and JavaScript files that were attached to the source code of the website during its coding process. Firstly, the URL of the website needed to be scrape
2 min read
How to use Scrapy to parse PDF pages online?
Prerequisite: Scrapy, PyPDF2, URLLIB In this article, we will be using Scrapy to parse any online PDF without downloading it onto the system. To do that we have to use the PDF parser or editor library of Python know as PyPDF2. PyPDF2 is a pdf parsing library of python, which provides various methods like reader methods, writer methods, and many mor
3 min read
Delete pages from a PDF file in Python
In this article, We are going to learn how to delete pages from a pdf file in Python programming language. Introduction Modifying documents is a common task performed by many users. We can perform this task easily with Python libraries/modules that allow the language to process almost any file, the possibility of data processing inside Programming
4 min read
How to count the number of pages in a PDF file in Python
In this article, we will see how can we count the total number of pages in a PDF file in Python, For this article there is no such prerequisite, we will use PyPDF2 library for this purpose. PyPDF2 is a free and open-source pure-Python PyPDF library capable of performing many tasks like splitting, merging, cropping, and transforming the pages of PDF
4 min read
How to Build Portfolio Website And Host It on GitHub Pages?
Having an online portfolio is important for showcasing your skills and accomplishments. GitHub Pages provides a convenient and free platform for hosting your portfolio website. In this article, we will see how to build a Portfolio Website And Host It on GitHub Pages. Table of Content Creating a Portfolio WebsiteUploading into a GitHub RepositoryCre
15 min read
Project Idea | Website Generator using Facebook/Instagram Page
Project Title: Website Generator using their Facebook/Instagram Page Introduction: The Idea is to provide a website for those students who make their Facebook /Instagram page or group and want to shift their data on a static website and want to be a good blogger. So, this framework provides them with a website without doing such painful work. Featu
1 min read
Integrating Facebook Like & Share Plugin Using Django
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. In this article we will learn to integrate facebook comment plugin in django.
2 min read
Download Facebook video using Python
In this article, we will learn how to create a user-friendly Python program to download Facebook videos using the video URL. Using Python programming, there are several ways to solve the same problem. we going to use a Python module called 'youtube_dl' to achieve the target. Description of modules and methods used Before diving into the solution, l
4 min read
Facebook Login using Python
Python scripting is one of the most intriguing and fascinating things to do meanwhile learning Python. Automation and controlling the browser is one of them. In this particular article, we will see how to log in to the Facebook account using Python and the power of selenium. Selenium automates and controls browsers and it's activity. We can code in
4 min read
Facebook API | Set-2
Prerequisite - Facebook API | Set-1In this article, we will be discussing the implementation details of the Facebook API for Python Platform. Let's begin with downloading Facebook Client for Python. Use following python command to download Facebook Client- pip install facebook-sdk Upon successful download you will see a screen like this- Now, let's
4 min read
How Did Facebook Remove 2.2 Billion Fake Accounts in the First Quarter of 2019?
Ever heard of Facebook? Well, unless you have been living under a rock this past decade, I'm sure you have. And in case you haven't, Facebook is a social networking site that is used to share pictures, post comments on the aforementioned pictures, watch news (only if extremely bored!), chat live with people, watch short-form videos, etc. (Although
4 min read
Facebook API | Set-3
Prerequisite: Facebook API | Set-1, Set-2 In this article we will be discussing three methods: search get_connections get_allconnections search method: The valid value types are place and placetopic. Parameters: id: It is a string containing a valid value. args: This is optional and they need to passed a query params. Example: Get details of all pl
3 min read
5 Mind-Blowing Ways Facebook Uses Machine Learning
What comes first to mind when you think about social networking? It's Facebook of course! There is even a movie called The Social Network that proves this statement! And with 2.91 Billion Monthly Active Users in the third quarter of 2021, it’s safe to say that Facebook is actually not even a social network but a global phenomenon. And obviously, Ma
9 min read
Integrating Facebook Comments Plugin in Django Project
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. In this article, we will learn to integrate the Facebook comment plugin in Dj
2 min read
Integrating Facebook Like, Comments and Share Plugin in Flask Project
Flask is a Framework of Python that allows us to build up web-applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. This article revolves around how to integrate Facebook comments plugin in flask ap
2 min read
OAuth Authentication with Flask - Connect to Google, Twitter, and Facebook
In this article, we are going to build a flask application that will use the OAuth protocol to get user information. First, we need to understand the OAuth protocol and its procedure. What is OAuth? OAuth stands for Open Authorization and was implemented to achieve a connection between online services. The OAuth Community Site defines it as “An ope
8 min read
Facebook API | Set-4
Prerequisites: Facebook API Set-1, Set-2, Set-3 In this article we will be discussing 3 methods : put_object put_like put_comment put_object: Writes the mentioned object to the Facebook Social Graph connected to the given parent. Parameters: parent_object: A string specifying the parent of the new object. For example- Post is the parent of comment,
2 min read
Selenium Base Mini Project Using Python
Project Description:-Here, we're going to study a simple SMS bomber trick (for amusing and educational purpose). Selenium is a free tool for automated trying out across exceptional browsers. In this tutorial, we will learn how to ship mechanically range of unsolicited mail SMS for given variety of frequency and interval. Requirement: You need to in
2 min read
Get all text of the page using Selenium in Python
As we know Selenium is an automation tool through which we can automate browsers by writing some lines of code. It is compatible with all browsers, Operating systems, and also its program can be written in any programming language such as Python, Java, and many more. Selenium provides a convenient API to access Selenium WebDrivers like Firefox, IE,
3 min read
Close specific Web page using Selenium in Python
Prerequisites: Selenium Basics, Selenium close() and quit() Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. The close() meth
2 min read
Download Instagram Posts Using Python Selenium module
In this article, we will learn how we can download Instagram posts of a profile using Python Selenium module. Requirements:Google Chrome or FirefoxChrome driver(For Google Chrome) or Gecko driver(For Mozilla Firefox)Selenium package: It is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on
7 min read
Scrape and Save Table Data in CSV file using Selenium in Python
Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make
3 min read