Запуск бота с селеном, который любит посты автоматически - PullRequest
0 голосов
/ 24 апреля 2020

Я пытаюсь запустить бота, которому автоматически нравятся все сообщения в ленте instagram.

Я получил бота до того момента, когда он:

-> открывает Google Chrome

-> Вход в систему и

-> Нравится первое сообщение.

Однако симпатия первого поста работает только тогда, когда я кодирую бота непосредственно в терминале без классов и создаю бота как объект. Или же это работает с решением 2 - посмотрите мой фрагмент кода - но потом после того, как подобное браузер закрывается сразу.

Я уже много чего пробовал:

-> Убедитесь, что есть достаточно времени между каждым шагом

-> Убедитесь, что все xpath названы правильно

-> Избегайте синтаксических ошибок, таких как "find__element s __ by __ (. ..)

Но теперь у меня закончились идеи ..

Вот мой код:

# Import Selenium and Webdriver to connect and interact with the Browser
from selenium import webdriver

# Import time package and sleep function in order to let the website load when it opens
from time import sleep

# Import username and password
from secrets import username, password

# Create the LikingBot Class
class LikingBot():

    def __init__(self):

        # Past the Directory where the chromediver is in order to run it
        self.driver = webdriver.Chrome('/Users/anwender/Coding/Python_Projects/Automation/Chrome_Webdriver/chromedriver')



    # --> Type "python3 -i main.py" in the Terminal and start developing

    def login(self):

        # 1) Go to Instagram main website
        self.driver.get('https://www.instagram.com/')

        # 1.1) Give the Website time to load; otherwise the following steps wont work
        sleep(2)

        # 2) Select the Email Login Box
        email_login = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div[2]/div[1]/div/form/div[2]/div/label/input')

        # 3) Interact with the Email Login Box and type in the Email address or the Username
        email_login.send_keys(username)

        # 4) Repeat step 2) & 3) with the Password Box
        password_login = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div[2]/div[1]/div/form/div[3]/div/label/input')
        password_login.send_keys(password)

        # 5) Click Log In Button
        login_btn = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div[2]/div[1]/div/form/div[4]/button') 
        login_btn.click()

        sleep(5)

        # 6) Click Activate Messages Button if it pops up
        activate_btn = self.driver.find_element_by_xpath('/html/body/div[4]/div/div/div[3]/button[1]')
        activate_btn.click()


    # Writing the automatic liking function
    def auto_like(self):

        """
        Here are the elements for the automation liking. It seems like every article has the same xpath of the
        button. So the goal is to iterate through the articles with a for Loop, while the other attributes stay 
        the same!

        //*[@id="react-root"]/section/main/section/div[2]/div[1]/div/article[1]/div[2]/section[1]/span[1]/button
        //*[@id="react-root"]/section/main/section/div[2]/div[1]/div/article[2]/div[2]/section[1]/span[1]/button
        //*[@id="react-root"]/section/main/section/div[2]/div[1]/div/article[3]/div[2]/section[1]/span[1]/button
        //*[@id="react-root"]/section/main/section/div[2]/div[1]/div/article[..]/div[2]/section[1]/span[1]/button

        """

        sleep(2)

        # Start iteration
        article_iteration = 1


        # First Solution

        '''
        ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        like_buttons stores the xpath of the first like button. However it is not working even the xpath is absolutely right.

        like_buttons = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/section/div[2]/div[1]/div/article['+str(article_iteration)+']/div[2]/section[1]/span[1]/button')
        like_buttons.click()
        ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        '''


        # Second Solution

        '''
        ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        This like_buttons variable stores the same button element but takes the class name. It is working but after the like the browser closes.

        like_buttons = self.driver.find_element_by_class_name('wpO6b ')
        like_buttons.click()
        ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        '''


        # Write the liking loop

        '''
        ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        while True:
            like_buttons.click()
            article_iteration += 1
        ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        '''

# Initialize Bot
bot = LikingBot()
bot.login()
bot.auto_like()

Любая помощь приветствуется и, надеюсь, кто-то может помочь!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...