Last active
December 23, 2023 02:26
-
-
Save davidcairuz/062105c866e128610e448e32856c2049 to your computer and use it in GitHub Desktop.
Instagram bot to like photos
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from selenium import webdriver | |
from selenium.webdriver.common.keys import Keys | |
import time | |
class InstagramBot: | |
def __init__(self, username, password): | |
self.username = username | |
self.password = password | |
self.driver = webdriver.Firefox(executable_path='C:\geckodriver.exe') | |
def close_browser(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) | |
username_box = driver.find_element_by_xpath("//input[@name='username']") | |
password_box = driver.find_element_by_xpath("//input[@name='password']") | |
username_box.clear() | |
username_box.send_keys(self.username) | |
password_box.clear() | |
password_box.send_keys(self.password) | |
password_box.send_keys(Keys.RETURN) | |
time.sleep(2) | |
def like_hashtag(self, hashtag): | |
driver = self.driver | |
driver.get("https://www.instagram.com/explore/tags/{}/".format(hashtag)) | |
time.sleep(5) | |
photos_url = [] | |
for i in range(10): | |
try: | |
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") | |
time.sleep(3) | |
visible_url = driver.find_elements_by_tag_name("a") | |
visible_url = [url.get_attribute('href') for url in visible_url | |
if '.com/p/' in url.get_attribute('href')] | |
[photos_url.append(url) for url in visible_url if url not in photos_url] | |
except Exception: | |
continue | |
# Start liking photos | |
total_photos = len(photos_url) | |
for photo in photos_url: | |
driver.get(photo) | |
time.sleep(2) | |
print("Currently on #{}: {} photos remaining...".format(hashtag, total_photos)) | |
total_photos -= 1 | |
try: | |
heart_xpath = "/html/body/span/section/main/div/div/article/div[2]/section[1]/span[1]/button" | |
heart_button = driver.find_element_by_xpath(heart_xpath) | |
heart_button.click() | |
time.sleep(2) | |
except Exception: | |
print('Failed.') | |
time.sleep(2) | |
username = 'USERNAME' | |
password = 'PASSWORD' | |
user = InstagramBot(username, password) | |
user.login() | |
interests = ['love', 'photography', 'photo', 'games', 'spiderman', 'art', 'marvel', | |
'tech', 'travel', 'landscape', 'happy', 'movies', 'newyork', 'france', | |
'makeup', 'model', 'arte', 'world', 'beautiful', 'italy', 'youtube'] | |
for interest in interests: | |
user.like_hashtag(interest) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment