Enes A.
Enes A.

Reputation: 1

I have a problem with a Instagram like bot with Python Selenium

Hey guys I am new into python, I learned java and Pascal and yea I wanted to learn how to use instagram bots with python and watched a youtube video, but my problem is that the bot just picks pictures and switches to the next one without liking it, so I think it can't find the like button.

I think the problem is somewhere at # Liking photos I tried changing the xpath a lot of times but it doesn't end up liking a picture. Thanks in advance

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
import time
import random
import sys


def print_same_line(text):
    sys.stdout.write('\r')
    sys.stdout.flush()
    sys.stdout.write(text)
    sys.stdout.flush()


class InstagramBot:

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.driver = webdriver.Chrome()

    def closeBrowser(self):
        self.driver.close()

    def login(self):
        driver = self.driver
        driver.get("https://www.instagram.com/")
        time.sleep(3)
       #login_button = driver.find_element_by_xpath("//a[@href='/accounts/login/']")
       #login_button.click()
        time.sleep(2)
        user_name_elem = driver.find_element_by_xpath("//input[@name='username']")
        user_name_elem.clear()
        user_name_elem.send_keys(self.username)
        passworword_elem = driver.find_element_by_xpath("//input[@name='password']")
        passworword_elem.clear()
        passworword_elem.send_keys(self.password)
        passworword_elem.send_keys(Keys.RETURN)
        time.sleep(2)


    def like_photo(self, hashtag):
        driver = self.driver
        driver.get("https://www.instagram.com/explore/tags/" + hashtag + "/")
        time.sleep(2)

        # gathering photos
        pic_hrefs = []
        for i in range(1, 4):
            try:
                driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
                time.sleep(2)
                # get tags
                hrefs_in_view = driver.find_elements_by_tag_name('a')
                # finding relevant hrefs
                hrefs_in_view = [elem.get_attribute('href') for elem in hrefs_in_view
                                 if '.com/p/' in elem.get_attribute('href')]
                # building list of unique photos
                [pic_hrefs.append(href) for href in hrefs_in_view if href not in pic_hrefs]
                # print("Check: pic href length " + str(len(pic_hrefs)))
            except Exception:
                continue

        # Liking photos
        unique_photos = len(pic_hrefs)
        for pic_href in pic_hrefs:
            driver.get(pic_href)
            time.sleep(2)
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            try:
             time.sleep(random.randint(2, 4))
             #I think the problem is somewhere at the xpath
             like_button = lambda:  driver.find_element_by_xpath("//button/span[@aria-label='Like']").click()
             like_button().click()
             time.sleep(2)

                for second in reversed(range(0, random.randint(18, 28))):
                    print_same_line("#" + hashtag + ': unique photos left: ' + str(unique_photos)
                                    + " | Sleeping " + str(second))
                   time.sleep(1)
            except Exception as e:
                time.sleep(2)
            unique_photos -= 1

if __name__ == "__main__":

    username = "USERNAME"
    password = "PASSWORD"

    enesIG = InstagramBot("myIGloginname", "myIGPassword")
    enesIG.login()
    enesIG.like_photo('newyork')

    hashtags = ['amazing', 'beautiful', 'adventure', 'photography', 'nofilter',
                'newyork', 'artsy', 'alumni', 'lion', 'best', 'fun', 'happy',
                'art', 'funny', 'me', 'followme', 'follow', 'cinematography', 'cinema',
                'love', 'instagood', 'instagood', 'followme', 'fashion', 'sun', 'scruffy',
                'street', 'canon', 'beauty', 'studio', 'pretty', 'vintage', 'fierce']

    while True:
        try:
            # Choose a random tag from the list of tags
            tag = random.choice(hashtags)
            ig.like_photo(tag)
        except Exception:
            ig.closeBrowser()
            time.sleep(60)
            enesIG = InstagramBot(username, password)
            enesIG.login()

The current Error is this one. And when I change the xpath on the like button there are other errors.

C:\Python38-32>Instagram_Bot3.py
  File "C:\Python38-32\Instagram_Bot3.py", line 78
    for second in reversed(range(0, random.randint(18, 28))):
    ^
IndentationError: unexpected indent

Upvotes: -1

Views: 733

Answers (1)

scilence
scilence

Reputation: 1115

Give this xpath a shot

//*[name()='svg'][@aria-label='Like']/parent::button

What you were trying to access as a span is actually an svg element, so this seems to find it accurately. You may run into some other issues. When testing locally I ended up using

like_button = driver.find_element_by_xpath("//*[name()='svg'][@aria-label='Like']/parent::button")
driver.execute_script("arguments[0].click()", like_button)

Which uses javascript to click the 'like' button. This seems to work fairly reliably.

Also, that error you referenced is solely due to how your code is formatted. I was able to fix that when testing your code locally by copying the whitespace before the line above it and pasting it into that line, but you really should use tabs consistently. Mixing tabs and spaces can get annoying with Python.

Upvotes: 0

Related Questions