Skip to content

Instantly share code, notes, and snippets.

@tacomonster
Last active January 29, 2024 10:02
Show Gist options
  • Save tacomonster/555bceef3d14673810f625edd000c112 to your computer and use it in GitHub Desktop.
Save tacomonster/555bceef3d14673810f625edd000c112 to your computer and use it in GitHub Desktop.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
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(2)
login_button = driver.find_element_by_xpath("//a[@href='/accounts/login/?source=auth_switcher']")
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, 7):
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))
like_button = lambda: driver.find_element_by_xpath('//span[@aria-label="Like"]').click()
like_button().click()
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"
ig = InstagramBot(username, password)
ig.login()
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)
ig = InstagramBot(username, password)
ig.login()
@SinclairPythonAkoto
Copy link

does anyone know how to actually like & follow a profile? I tried changing the xpath and even removing the 'com' in line 57 and still end up with the same result. the bot logs in successfully and scrolls through the hashtags but it just doesn't appear to be linking the pictures..

If anyone can help me out that would be great !

@SinclairPythonAkoto
Copy link

Hi all, here is my new repo for instagram to like & post comments.
https://github.com/RGV2/InstaBot
Don't forgot to give STAR...

I just downloaded and tried your program and it worked brilliantly!! Thanks !!

..I wanted to know if I could make the bot click the follow button as well?? please help ! many thanks 🙏

@RGV2
Copy link

RGV2 commented Jul 25, 2020

Hi all, here is my new repo for instagram to like & post comments.
https://github.com/RGV2/InstaBot
Don't forgot to give STAR...

I just downloaded and tried your program and it worked brilliantly!! Thanks !!

..I wanted to know if I could make the bot click the follow button as well?? please help ! many thanks 🙏

Sure, I will add this feature in next release. :)

@SinclairPythonAkoto
Copy link

I have been up all night looking through stackoverflow and managed to find a way to add a follower.. seeing how I am relatively new to this you might have a different way or slightly easier way.. im sure you will understand the process more than me.. lol

basically within the like_comment( ) function I done:

sleep(random.randint(2, 4))
follow_button = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//button[text()='Follow']")))
follow_button.click()
sleep(2)

and then at the top I imported:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

This worked very well along with your code! I have been getting a lot of interactions and a few follow backs already so again thank you! :)

Would you mind if I put this version on my Github? I will state how I got the original repo from you and share a link to your repo..

thanks

@Nicolassalazar-pro
Copy link

Hey so actually instead of liking posts I would just like to see how many likes the top 9 posts get. could someone help me with this?

@lqveme
Copy link

lqveme commented Aug 30, 2020

I have been up all night looking through stackoverflow and managed to find a way to add a follower.. seeing how I am relatively new to this you might have a different way or slightly easier way.. im sure you will understand the process more than me.. lol

basically within the like_comment( ) function I done:

sleep(random.randint(2, 4))
follow_button = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//button[text()='Follow']")))
follow_button.click()
sleep(2)

and then at the top I imported:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

This worked very well along with your code! I have been getting a lot of interactions and a few follow backs already so again thank you! :)

Would you mind if I put this version on my Github? I will state how I got the original repo from you and share a link to your repo..

thanks

could you post this version or send me it?
Is it still working ?
thank you!

@ticmali
Copy link

ticmali commented Sep 7, 2020

Hi all, here is my new repo for instagram to like & post comments.
https://github.com/RGV2/InstaBot
Don't forgot to give STAR...

Bot stil doesn't Likes pictures. help?

@RGV2
Copy link

RGV2 commented Sep 8, 2020

Hi all, here is my new repo for instagram to like & post comments.
https://github.com/RGV2/InstaBot
Don't forgot to give STAR...

Bot stil doesn't Likes pictures. help?

Can you please elaborate a little bit, are you getting any type of error?

@ticmali
Copy link

ticmali commented Sep 9, 2020

Can you please elaborate a little bit, are you getting any type of error?

fixed!

oh my mistake, it was bcs Chrome was on different language! sry :D

@RGV2
Copy link

RGV2 commented Sep 12, 2020

Can you please elaborate a little bit, are you getting any type of error?

fixed!

oh my mistake, it was bcs Chrome was on different language! sry :D

Please get a new pull, I have fixed that.
And don't miss to hit star on my repo :).

@ticmali
Copy link

ticmali commented Sep 12, 2020

Can you please elaborate a little bit, are you getting any type of error?

fixed!
oh my mistake, it was bcs Chrome was on different language! sry :D

Please get a new pull, I have fixed that.
And don't miss to hit star on my repo :).

nice job m8 :) thx

@RGV2
Copy link

RGV2 commented Sep 16, 2020

Hi all, please check out my repo (https://github.com/RGV2/InstaBot). I've updated this as most of the users are not able to open the hashtag explorer page. So, just put the hashtag status to false in the config.json file, after this the bot will fetch the posts from the explorer page. In addition you can set the comment status to true or false.

@RGV2
Copy link

RGV2 commented Sep 17, 2020

Hi all, here is my new repo for instagram to like & post comments.
https://github.com/RGV2/InstaBot
Don't forgot to give STAR...

I just downloaded and tried your program and it worked brilliantly!! Thanks !!

..I wanted to know if I could make the bot click the follow button as well?? please help ! many thanks 🙏

You can check the new code, I have added the follow feature and lot more.

@grgrego07
Copy link

Capture

I am not able to locate the element via the firefox inspector.
Any idea how to fix this?

@pedrosouzax
Copy link

@grgrego07

Maybe you need give time to locate the element. You can import

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import presence_of_element_located

and before you try to click or to send keys, you should do something like this:

wait = WebDriverWait(driver, 10)
wait.until(presence_of_element_located((By.NAME, 'the-name-of-your-element')))

for example.

@grgrego07
Copy link

anyone that can share a working version of the code? so i can plug in my details??
Looks i am doing something wrong.

@ticmali
Copy link

ticmali commented Oct 28, 2020

can you make bot for massive Unfollow? thx

@VachaArraniry
Copy link

can you make the bot to auto-reply messages in Instagram dms

@Irvinelavine
Copy link

ISSUE CLOSED!

It works most of the time, sometimes this bottom login comes up now! This might be while I am on temporary ban only, but I'm not positive.
Screen Shot 2019-06-10 at 3.12.52 PM.png

Right now one of my accounts is running, but the other one keeps running into this screen, it is such a weird situation and not exactly always repeatable so I'm not quite sure how we are going to tackle this.

The weird thing is it shows up after the bot actually logs in? Maybe this is a glitch with the Instagram site itself because it would happen only 1-100 now it happens more, and now 100% on one of my accounts!

It is working now after re-launch but wondering if anyone else noticed this and if so has a solution, or knows what is going on?

Screen Shot 2019-06-10 at 3.38.34 PM.png

The fix to this error in the first screenshot was simply clearing the cache and cookies in Firefox browser! minor! lol

The bot is working great!

Had this problem because I opened another session. only declare webdriver under init

@Irvinelavine
Copy link

can someone pls explain what this section is doing exactly
for i in range(1, 7):

@Aadit017
Copy link

hmmm. I cannot seem to get the code to work on my mac. Can anyone assist? It might be related to the python my computer is using?

Now I have this error message on PyCharm:
/Users/student/PycharmProjects/youtube/venv/bin/python "/Users/student/Desktop/youtube vid/instagram.py"
File "/Users/student/Desktop/youtube vid/instagram.py", line 1
import selenium from webdriver
^
SyntaxError: invalid syntax

Process finished with exit code 1

sir its from selenium import webdriver

@colorado2019
Copy link

How do you add the comments.txt, config.json and hashtags.txt to the code? I am receiving the following error: FileNotFoundError: [Errno 2] No such file or directory: './instaRes/config.json'

I am able to login, but I am kicked out right away. Thank you

@cdeberry4
Copy link

cdeberry4 commented Dec 29, 2020

Everything works for me except the actual liking part. The program opens up the picture and never actually likes it
Screen Shot 2020-12-28 at 8 13 37 PM

@pip-pipo
Copy link

its worked owww really supwe

@djmart31
Copy link

can you do it without needing a password, just by username?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment