Python Selenium 如果找不到则跳到下一步

Python Selenium skip to next step if not found

我制作了一个简单的 IG 机器人,它转到指定的标签,由 post 转到 post,点赞,然后关注 post 人。但有时 Instagram 会崩溃并且不显示 post - 然后脚本也会崩溃,因为它找不到 follow/like 按钮。

如果找不到按钮,我可以做一个循环或其他东西吗,单击下一个post按钮?我是 python 的新手,我搞不懂。

这是我的代码:

# 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()

此代码应该有效,它会尝试执行,如果我不起作用,请转到下一个 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()