mardi 18 août 2020

python selenium instagrambot - for i in range loop (if statement)

Pardon me im a noobie what it comes to coding. okay so my problem is about for i in loop, I couldnt find answer from anywhere and tried many different thing so I decided to ask from here.

so basically the bot goes for 1 hashtag and clicks on picture and after that it keeps liking and following them in order and the problem comes when Ive already followed that person. so I tried to go for the (if) statement to unfollow if its already followed.

the loops goes fine for one round for example lets say the first picture it goes for like and then follows.. after that it doesnt click the next arrow and it clicks like and unfollow but this time it gets error because reasons?

pardon me I couldnt get the code look any cleaner than this + im not sure if (else:) is needed here.

code:`

import selenium
from selenium import webdriver
from time import sleep
PATH = "C:\Program Files (x86)\chromedriver.exe" 
driver = webdriver.Chrome(PATH)
driver.get("https://instagram.com")
sleep(4)
driver.find_element_by_xpath(("//input[@name=\"username\"]"))\
.send_keys(("usernamehere"))
driver.find_element_by_xpath(("//input[@name=\"password\"]"))\
.send_keys(("passwordhere"))
driver.find_element_by_xpath(('//*[@id="loginForm"]/div/div[3]/button'))\
    .click()
sleep(4)
driver.find_element_by_xpath(('//*[@id="react-root"]/section/main/div/div/div/div/button'))\
    .click()
driver.find_element_by_xpath(('/html/body/div[4]/div/div/div/div[3]/button[2]'))\
    .click()
hashtag_input = driver.find_element_by_xpath(('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/input'))
hashtag_input.send_keys("hashtagsomething")
sleep(2)
driver.find_element_by_xpath(('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/div[3]/div[2]/div/a[1]'))\
    .click()
sleep(4)
#clicks first picture
driver.find_element_by_xpath(('//*[@id="react-root"]/section/main/article/div[1]/div/div/div[3]/div[1]/a/div'))\
    .click()
sleep(2)
for i in range(100):
    #likes
 driver.find_element_by_xpath("/html/body/div[4]/div[2]/div/article/div[3]/section[1]/span[1]
/button")\
    .click()
    sleep(2)
    #follows
    driver.find_element_by_xpath("/html/body/div[4]/div[2]/div/article/header/div[2]/div[1]/div[2]/button")\
    .click()
    sleep(2)
    #if already following
myelement = driver.find_element_by_xpath("/html/body/div[5]/div/div/div/div[3]/button[1]")
if  myelement.is_displayed():
    myelement.click()
    # clicksnextarrow
else: driver.find_element_by_xpath("/html/body/div[4]/div[1]/div/div/a[2]")\
.click()
sleep(3)

`

thanks for your time

Aucun commentaire:

Enregistrer un commentaire