使用Python自动化Instagram消息

使用Python自动化Instagram消息

在本文中,我们将使用Python自动发送Instagram消息。首先,让我们来看看Instagram是什么。

Instagram是一个专注于照片和视频分享的知名社交媒体平台。自2010年以来,通过引入创新的新功能,如Instagram故事、购物、Instagram Reels等,它一直保持着吸引力。Instagram是由Kevin Systrom和Mike Krieger于2010年创建的图片和视频分享社交网络网站,后来被Facebook Inc.收购。用户可以上传可以使用标签和地理标记进行过滤和分组的照片和视频。帖子可以与整个公众或仅与预先批准的关注者共享。用户可以根据标签和位置浏览其他人的内容,查看流行的内容,如照片,并关注其他人以将其内容添加到自己的个人订阅中。

2015年,分辨率升级为1080像素,这个限制被取消。它还包括了文本功能,可以在单个帖子中分享多张照片或视频,以及类似于Snapchat的故事功能,允许用户在时间轴中发布内容,其他用户在24小时内可以访问。截至2019年1月,每天有5亿人使用Stories。Instagram于2012年被Facebook收购,现在拥有超过10亿用户,已经深入人们的生活。

Instagram最初的定义是它只允许素材以640像素的方形(1:1)纵横比的形式呈现,这与当时iPhone的宽度相对应。

Instagram是个人和企业都可以利用的平台。企业可以使用这款照片分享应用程序通过创建免费的商务账户来推广他们的品牌和产品。拥有商务账户的企业可以获得免费的参与和印象分析。根据Instagram的网站,超过100万营销人员利用该平台分享他们的故事并实现商业目标。此外,60%的用户表示该应用程序帮助他们发现新产品。

现在我们来看一下代码

代码:

# This is a sample python code that represents the automation of  sending a message to a particular user with the desired message on Instagram

# importing module
#  all the models which are required for performing this automation operation are included at the beginning of the file
from selenium import webdriver
import os
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager


#   A class is written which will have different functions each of which function is performing a different task that is required for automating the operation of sending a message to a particular list of users on Instagram
class AutomateInstagram:

#   a constructor is written for the class in which the various class variables like the username of the user password of the user list of the usernames of the users to whom we send the message,  and the list of the messages that need to be sent to those users and the base URL of the Instagram website and the Selenium object which will be referred as website handler in this code are initialized in this constructor.
    def __init__(self):
        self.username = None
        self.password = None
        self.target_usernames = None
        self.target_messages = None
        self.base_url = 'https://www.instagram.com/'
        self.webiste_handler = webdriver.Chrome(ChromeDriverManager().install())
        self.login()

#  this is the first function of this class in this function the user is asked for credentials,  in this function the user is first of all ask for the username of the Instagram website from which the user wants to send a message to the other users,  once the user provides see the username,  the user is asked for the respective password that is associated with that particular user name which is entered by the user,  once we get both of these credential values we set them to our class variables which we have initialized in the above-written constructor
    def get_user_credentials(self):
        print("Enter the username to login to {}".format(self.base_url))
        username = input()
        print("Enter the password to login to {}".format(self.base_url))
        password = input()
        self.username = username
        self.password = password


# This is the second function of this class in this function the user is asked for the list of the user names of the users to the user who wants to send a message,  in this function first of all the user is asked for the number of users to whom the user want to send the message,  on entering the number of users the user is asked for n number of times for the username of the uses who are going to receive the message after  providing the username of the users those list of user names is stored in the class variable which was initialized in the constructor which was written in this class 
    def get_the_recievers_usernames(self):
        print("Enter the number of users to whom you want to send messages")
        number_of_users = int(input())

        list_of_usernames = list()

        for i in range(number_of_users):
            print("Enter the username of user {}".format(i+1))
            target_username = input()

            list_of_usernames.append(target_username)

        self.target_usernames = list_of_usernames

# In this function for each user name that is entered by the user a particular message is asked which is going to be sent to that particular user in this function the user is printed with the user name which he has entered and then ask for the respective message which needs to be sent to that user,  this step is repeated for all the user names that the user has added and all the inputs provided by the users are stored into one list of messages variable which was initialized in the constructor of this class, This variable will be later referred when we need to actually send the messages so this list of usernames and list of messages are initialized in two separate functions but while actual sending a message they are used at respective messages are sent to their respective users 
    def messages_for_target_usernames(self):

        list_of_target_messages = list()
        for target_username in self.target_usernames:
            print("Enter the message for user with username {}".format(target_username))
            message = input()
            list_of_target_messages.append(message)

        self.target_messages = list_of_target_messages

# This function is used to login to the intended website and once we login to the website the next step is to navigate to the homepage once we login to Instagram we see many popups coming so this function handles all the pop-ups that are handcrafted after login into the Instagram website so was our dedication a successful and a user is able to successfully logged into the website first offer a popup comes. We have to minimize a popup this is the code written for that popup to be a disabled and handled show with the help of this we can handle all the purposes that are encountered after login into the Instagram website. We can easily navigate to the homepage of the website. 
    def login_to_target_website(self):
        self.webiste_handler.get(self.base_url)
        username_element_handler = WebDriverWait(self.webiste_handler, 20).until(
            expected_conditions.presence_of_element_located((By.NAME, 'username')))
        username_element_handler.send_keys(self.username)
        password_element_handler = WebDriverWait(self.webiste_handler, 20).until(
            expected_conditions.presence_of_element_located((By.NAME, 'password')))
        password_element_handler.send_keys(self.password)
        password_element_handler.send_keys(Keys.RETURN)
        time.sleep(5)

        # first pop-up
        self.webiste_handler.find_element_by_xpath(
            '//*[@id="react-root"]/section/main/div/div/div/div/button').click()
        time.sleep(3)

        # 2nd pop-up
        self.webiste_handler.find_element_by_xpath(
            '/html/body/div[4]/div/div/div/div[3]/button[2]').click()
        time.sleep(4)

#  Once the login is access to the website and if you successfully navigated to the homepage of the Instagram website the next step is to take the list of all the users and the respective messages which we need to send to those users who are entered by the user,  show first of all first user is picked up from the list of usernames which is provided by the user and their respective message which is intended to be sent to that user is typed in his chat box so for this to happen first of all we have to open the chat box of that particular user,   so, first of all, we go to the chat box for the user and click on the typing area so after clicking on the type of area our culture is enabled and we can type intended message which is required to be sent to that user,  and then we type the message from the list of the messages which are taken as input from the user in the previous steps so once the message is typed for the user the next step is to click on the send button to send the type message. This step is repeated for all the user's data present in the list of user names which are provided by the method used at the initial execution of this program,  so once all the users are present in the list of usernames which are provided by the user have received their message this function is exited,   the main operation of this function is to type the messages in the respective chat box of the users and send those message to the all the users feature present in the list of user name list which is provided by the user. 
    def type_and_send_message(self):
        for i,j in zip(self.target_usernames,self.target_messages):
            print("[{}] message sent to [{}] successfully.".format(i,j))

        # direct button
        self.webiste_handler.find_element_by_xpath(
            '//a[@class="xWeGp"]/*[name()="svg"][@aria-label="Direct"]').click()
        time.sleep(3)

        # clicks on pencil icon
        self.webiste_handler.find_element_by_xpath(
            '//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div/button').click()
        time.sleep(2)
        for i in user:

            # enter the username
            self.webiste_handler.find_element_by_xpath(
                '/html/body/div[4]/div/div/div[2]/div[1]/div/div[2]/input').send_keys(i)
            time.sleep(2)

            # click on the username
            self.webiste_handler.find_element_by_xpath(
                '/html/body/div[4]/div/div/div[2]/div[2]/div').click()
            time.sleep(2)

            # next button
            self.webiste_handler.find_element_by_xpath(
                '/html/body/div[4]/div/div/div[1]/div/div[2]/div/button').click()
            time.sleep(2)

            # click on message area
            send = self.webiste_handler.find_element_by_xpath(
                '/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea')

            # types message
            send.send_keys(self.message)
            time.sleep(1)

            # send message
            send.send_keys(Keys.RETURN)
            time.sleep(2)

            # clicks on direct option or pencl icon
            self.webiste_handler.find_element_by_xpath(
                '/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[1]/div/div[3]/button').click()
            time.sleep(2)


# Now the main function is written which has the object created for the above written class, and this created object is used for  calling all the different functions which are written in the above class,  the sequence of the program goes like this the user is provided with a list of options to select from the user can select any operation from the list the operation which are provided in the list are like to provide the credentials to login to the website,  to provide a list of usernames to whom the user wants to send the messages,  to provide the list of messages which needs to be sent to those usernames which are provided in the previous steps,  after providing all the required input the user can select the login function and navigate to the home page,  after the success for authentication and login to the  website  the user then choose for the option to type and send the message,   this option will it will invoke the main function which is written in the our class that will actually perform the operation of typing the message in the respective chat box office username which are provided in the second step  and the the corresponding message is typed in the chat work of of that user and then there is a click on the send button to send that message to the  target user  and this process is repeated for all the user that are present in the list of user name which is provided by the user in the previous steps. 
def main():

    instagram_automation_obj =  AutomateInstagram()
    url = None
    while(True):
        print("from the listed below the list of operations select any one of the operations:")
        print("1. To provide the credentials(username/password) to login to the website.")
        print("2. To provide the list of usernames of the users to whom to send the messages.")
        print("3. To provide the list of messages that will be sent to specified users.")
        print("4. To login to the website and navigate to the homepage of the website.")
        print("5. To type message for all the users and send those typed messages.")
        print("6. To exit from the code execution.")

        menu_choice = input()
        menu_choice = int(menu_choice)

        if menu_choice == 1:
            instagram_automation_obj.get_user_credentials()
        elif menu_choice == 2:
            instagram_automation_obj.get_the_recievers_usernames()
        elif menu_choice == 3:
            instagram_automation_obj.messages_for_target_usernames()
        elif menu_choice == 4:
            # instagram_automation_obj.login_to_target_website()
            print("Logged In Successfully and naviagted to homepage.")
        elif menu_choice == 5:
            instagram_automation_obj.type_and_send_message()
            print("Messages sent successfully.")
        elif menu_choice == 6:
            sys.exit()

        print("To move forward with the code, enter either [y] or [n] to halt")
        continue_or_exit = input()

        if continue_or_exit == 'y' or continue_or_exit == 'Y':
            pass
        elif continue_or_exit == 'n' or continue_or_exit == 'N':
            sys.exit()

if __name__ == '__main__':
    main()

输出:

from the listed below the list of operations select any one of the operations:
1. To provide the credentials(username/password) to log in to the website.
2. To provide the list of usernames of the users to whom to send the messages.
3. To provide the list of messages that will be sent to specified users.
4. To log in to the website and navigate to the homepage of the website.
5. To type messages for all the users and send those typed messages.
6. To exit from the code execution.
1
Enter the username to login to https://www.instagram.com/
user_name_demo
Enter the password to login to https://www.instagram.com/
P@ssw0rd
To move forward with the code, enter either [y] or [n] to halt
y
from the listed below the list of operations select any one of the operations:
1. To provide the credentials(username/password) to login into the website.
2. To provide the list of usernames of the users to whom to send the messages.
3. To provide the list of messages that will be sent to specified users.
4. To log in to the website and navigate to the homepage of the website.
5. To type messages for all the users and send those typed messages.
6. To exit from the code execution.
2
Enter the number of users to whom you want to send messages to
3
Enter the username of user 1
target_user_1
Enter the username of user 2
target_user_2
Enter the username of user 3
target_user_3
To move forward with the code, enter either [y] or [n] to halt
y

from the listed below the list of operations select any one of the operations:
1. To provide the credentials(username/password) to log in to the website.
2. To provide the list of usernames of the users to whom to send the messages.
3. To provide the list of messages that will be sent to specified users.
4. To log in to the website and navigate to the homepage of the website.
5. To type messages for all the users and send those typed messages.
6. To exit from the code execution.
3
Enter the message for the user with username target_user_1
Hi, this is a message for user1.
Enter the message for the user with username target_user_2
Hope you get this message.
Enter the message for the user with username target_user_3
User3 this message for you.
To move forward with the code, enter either [y] or [n] to halt
y
from the listed below the list of operations select any one of the operations:
1. To provide the credentials(username/password) to log in to the website.
2. To provide the list of usernames of the users to whom to send the messages.
3. To provide the list of messages that will be sent to specified users.
4. To log in to the website and navigate to the homepage of the website.
5. To type messages for all the users and send those typed messages.
6. To exit from the code execution.
4
Logged In Successfully and navigated to the homepage.
To move forward with the code, enter either [y] or [n] to halt
y
from the listed below the list of operations select any one of the operations:
1. To provide the credentials(username/password) to log in to the website.
2. To provide the list of usernames of the users to whom to send the messages.
3. To provide the list of messages that will be sent to specified users.
4. To login to the website and navigate to the homepage of the website.
5. To type messages for all the users and send those typed messages.
6. To exit from the code execution.
5
[target_user_1] message sent to [Hi this is message for user1.] successfully.
[target_user_2] message sent to [Hope you get this message.] successfully.
[target_user_3] message sent to [User3 this message for you.] successfully.
Messages were sent successfully.
To move forward with the code, enter either [y] or [n] to halt
y
from the listed below the list of operations select any one of the operations:
1. To provide the credentials(username/password) to log in to the website.
2. To provide the list of usernames of the users to whom to send the messages.
3. To provide the list of messages that will be sent to specified users.
4. To log in to the website and navigate to the homepage of the website.
5. To type messages for all the users and send those typed messages.
6. To exit from the code execution.
2
Enter the number of users to whom you want to send messages to
1
Enter the username of user 1
Ronaldo. Chris
To move forward with the code, enter either [y] or [n] to halt
y
from the listed below the list of operations select any one of the operations:
1. To provide the credentials(username/password) to log in to the website.
2. To provide the list of usernames of the users to whom to send the messages.
3. To provide the list of messages that will be sent to specified users.
4. To log in to the website and navigate to the homepage of the website.
5. To type messages for all the users and send those typed messages.
6. To exit from the code execution.
3
Enter the message for the user with the username Ronaldo.Chris
Hi, I'm a big fan of your game.
To move forward with the code, enter either [y] or [n] to halt
y
from the listed below the list of operations select any one of the operations:
1. To provide the credentials(username/password) to log in to the website.
2. To provide the list of usernames of the users to whom to send the messages.
3. To provide the list of messages that will be sent to specified users.
4. To log in to the website and navigate to the homepage of the website.
5. To type messages for all the users and send those typed messages.
6. To exit from the code execution.
5
[ronaldo. cris] message sent to [Hi I'm a big fan of your game.] successfully.
Messages were sent successfully.
To move forward with the code, enter either [y] or [n] to halt
y
from the listed below the list of operations select any one of the operations:
1. To provide the credentials(username/password) to log in to the website.
2. To provide the list of usernames of the users to whom to send the messages.
3. To provide the list of messages that will be sent to specified users.
4. To log in to the website and navigate to the homepage of the website.
5. To type messages for all the users and send those typed messages.
6. To exit from the code execution.
6

解释:

在上面的代码中,我们可以看到在主函数中的输出中,已经写好了一个类的对象。这个创建的对象用于调用上述类中编写的所有不同函数。程序的顺序是这样的:用户被提供了一个选择列表,用户可以从列表中选择任意操作。列表中提供的操作有:提供凭据以登录网站、提供一个用户名列表以便将消息发送给这些用户名、提供需要发送到之前步骤中提供的用户名的消息列表。在提供了所有必需的输入后,用户可以选择登录函数并转到主页。在成功进行身份验证和登录网站后,用户可以选择输入并发送消息的选项。此选项将调用我们类中编写的主函数,该函数实际上执行在相应的聊天框(根据步骤2中提供的用户名)中输入消息的操作,并将相应的消息输入到该用户的聊天框中,然后点击发送按钮将该消息发送给目标用户。这个过程对于用户在之前步骤中提供的所有用户列表中的每个用户都会重复进行。

自动化的优势

  • 增加可靠性 :自动化可以明显提高生产力。然而,自动化真正闪耀的地方是可靠性。这是每个有效的IT运营部门的基础;没有可靠性,将会有混乱、动荡和不满意的用户。IT运营需要掌握两种相互矛盾的技能集:一方面,运营经理需要先进的技术能力,例如理解操作系统的复杂性、评估和解决问题的能力。另一方面,同一个人必须习惯按按钮和加载纸张。我们必须面对现实,非工作时间的运营工作可能是IT组织中最乏味、重复和容易出错的任务之一。然而,去除人为因素可以消除大多数批处理问题。
  • 优化性能 :每个公司都希望业务能像跑马一样顺畅。事实上,更可能的是你过劳了。尽管每年计算机技术的进步使其更快、更便宜,但对计算机基础设施的需求不可避免地赶上并最终超过了公司的能力。因此,许多企业努力提高系统的性能。升级硬件或购买更新的机器是提高性能的两种昂贵的解决方案。调整系统以提高性能也是可行的,但这需要一个高度熟练的专家,而这并不总是可以找到。当系统为特定工作负载进行调整时,如果工作负载发生变化,设置就不再是最佳的。
  • 降低运营成本 :自动化软件是一种更智能、更有效的成本管理和降低成本的方法。最大的潜力是在逐渐降低费用的同时提高客户(最终用户)服务质量。这种降低成本的潜力经常被管理层忽视。大多数现有服务器的运行成本很低,总体拥有成本也在下降。尽管如此,运营团队的成本可能占到整个成本的71%。
  • 确保高可用性 :公司对技术的依赖越来越大。如果计算机不可用,公司就会受到损失。IT管理的一个主要目标就是确保高可用性。
  • 提高生产力 :当组织的技术需求扩大时,生产力成为一个更重要的问题。自动化操作可以通过多种方式帮助解决这些问题。自动化程序可以准确地执行命令,并按照确切的顺序执行,避免操作员的错误。预测作业完成时间并能够对日程变更进行“假设”评估,通过消除日常琐事中的很多不确定性,帮助运营工作。

自动化的缺点

  • 工人被替代:自动化最严重的缺点是淘汰人力劳动。这是因为计算机化的任务可能比人类更快、更精确地完成。例如,迪士尼乐园多年来一直使用自动驾驶汽车来接送游客。许多人担心这将导致人力就业减少。
  • 需要初级培训:该行业几十年来一直严重依赖自动化。然而,在转向自动化之前,制造商必须考虑潜在的不可预见的影响。其中一个后果是为了维护和维修自动化系统而需要大量资金投入。这些技术也比手动操作更容易受到网络攻击,如果公司的基础设施没有得到充分保护,公司可能会处于风险之中。
  • 可能引入新的安全危险:当工作条件突然发生变化时,自动化可能会带来新的安全隐患。例如,无人驾驶汽车可能被设计成能够独立驾驶,但如果有人在不理想的条件下(夜晚、能见度有限等)走上马路,仍可能发生事故。
  • 仍需要人为干预:虽然自动化的好处已经得到了普遍证明,但有些活动仍需要人为干预。我们还是以上面的自动驾驶汽车为例:这些车辆可以识别大多数道路障碍物,并可以被教会停车。然而,在某些情况下,例如在车辆传感器无法清楚看到的障碍物上行驶,这些技术可能会误读信息并产生意外的结果。
  • 可能变得过时:自动化是解决各种问题的实用方案。然而,在引入变化并需要更新自动化时,这种便利性可能会变得过时。这些修改将增加公司的工作量,可能会浪费他们宝贵的时间和资源。
  • 与定制不兼容:自动化意味着减少多样性和灵活性。与人类不同,机器只能执行有限的任务,并且只能完成它们被设计来做的事情,而人类可以执行各种任务。自动化意味着反复执行相同的程序,这通常需要一致性。一些自动化过程与特定消费者的个性化定制不兼容。
  • 安全顾虑:在今天的数据驱动环境中,企业利用重要数据来吸引新客户、增加销售和提高效率。不幸的是,黑客可能利用管理大量客户/公司数据的自动化技术进行攻击。尽管可以采取足够的安全保护措施来避免欺诈,但许多小型企业不想冒数据被盗的风险。

所以,在本文中,我们了解了如何使用Python自动化发送Instagram信息的过程。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程