Skip to content

Instantly share code, notes, and snippets.

@trecno
Created December 13, 2021 19:05
Show Gist options
  • Save trecno/52808cf63de944aa6585e871b8492c59 to your computer and use it in GitHub Desktop.
Save trecno/52808cf63de944aa6585e871b8492c59 to your computer and use it in GitHub Desktop.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from datetime import datetime
from time import sleep
from sys import exit
import pandas as pd
import random
# Basic config
driver = webdriver.Firefox(executable_path='/usr/local/bin/geckodriver')
followed = pd.read_csv('followed.csv')
# Go to Instagram
sleep(2)
driver.get('https://www.instagram.com/accounts/login/')
sleep(3)
# Accept cookies
button_cookies = driver.find_element_by_xpath('/html/body/div[4]/div/div/button[1]')
button_cookies.click()
sleep(5)
# Log in
username = driver.find_element_by_name('username')
username.send_keys('usuario')
password = driver.find_element_by_name('password')
password.send_keys('p4ssw0rd')
button_login = driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]/button')
button_login.click()
sleep(7)
print('Logged in')
account_list = ['cuenta1','cuenta2'] # Accounts to process
supercounter = 1 # Counter of all followed accounts even if the loop files
def execute():
global supercounter
try:
#for account in account_list:
account = random.choice(account_list)
driver.get('https://www.instagram.com/'+ account)
sleep(5)
button_followers = driver.find_element_by_xpath('/html/body/div[1]/div/div/section/main/div/header/section/ul/li[2]/a')
button_followers.click()
sleep(5)
counter = 1
for _ in range(1, 66):
for _ in range(1, 4):
try:
label_username = driver.find_element_by_xpath('/html/body/div[6]/div/div/div[2]/ul/div/li[' + str(counter) + ']/div/div[2]/div[1]/div/div/span/a')
except:
label_username = driver.find_element_by_xpath('/html/body/div[6]/div/div/div[2]/ul/div/li[' + str(counter) + ']/div/div[1]/div[2]/div[1]/span/a')
username = label_username.text
print(str(supercounter) + ': ' + username)
try:
if not username in followed.username.values:
followed.loc[len(followed.index)] = [username, datetime.now(), pd.NaT]
try:
button_follow = driver.find_element_by_xpath('/html/body/div[6]/div/div/div[2]/ul/div/li[' + str(counter) + ']/div/div[3]/button')
except:
button_follow = driver.find_element_by_xpath('/html/body/div[6]/div/div/div[2]/ul/div/li[' + str(counter) + ']/div/div[2]/button')
button_follow.click()
print('Followed')
except:
pass
supercounter += 1
counter += 1
followed.to_csv('followed.csv', index = False)
for _ in range(2):
try:
driver.execute_script('document.querySelector(".PZuss > li:nth-child(' + str(counter + 1) + ')").scrollIntoView()')
except:
driver.execute_script('document.querySelector("li.wo9IH:nth-child(' + str(counter + 1) + ')").scrollIntoView()')
sleep(random.randint(10, 60))
except:
execute()
execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment