Home > Software engineering >  Python Selenium skip to next step if not found
Python Selenium skip to next step if not found

Time:03-18

I've made a simple IG bot that goes to indicated tag, goes post by post, likes, and follow the poster. But sometimes Instagram crashes and doesn't show the post - then script also crashes because it can't find a follow/like button.

Can I make a loop or something else if the button is not found, click the next post button? I'm totally new to python and I cant figure it out.

Here's my code:

# Following the poster
        if followtag:
            self.Wait(1,2)
            temp = self.driver.find_element_by_xpath('/html/body/div[6]/div[3]/div/article/div/div[2]/div/div/div[1]/div/header/div[2]/div[1]/div[2]/button')
            if (temp.text == "Obserwuj") and (name not in self.doNotFollowList):
                temp.click()
                self.AddFollowedList(name)
                self.AddDoNotFollowList(name)
                print("[{}] *followed* {}".format(i 1, name))

# Go to the next post
        if i == 0:
            self.driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div/button').click()
        else:
            self.driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div[2]/button').click()

CodePudding user response:

This code should work, It will try to follow and if i doesn't work, go to the next post.


    try:
        # Following the poster
        if followtag:
            self.Wait(1,2)
            temp = self.driver.find_element_by_xpath('/html/body/div[6]/div[3]/div/article/div/div[2]/div/div/div[1]/div/header/div[2]/div[1]/div[2]/button')
            if (temp.text == "Obserwuj") and (name not in self.doNotFollowList):
                temp.click()
                self.AddFollowedList(name)
                self.AddDoNotFollowList(name)
                print("[{}] *followed* {}".format(i 1, name))

    except:
        # Go to the next post
        if i == 0:
            self.driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div/button').click()
        else:
            self.driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div[2]/button').click()
  • Related