首页 > 解决方案 > 在 Python Selenium 中遍历列表元素

问题描述

这是我第一次发帖,所以如果我犯了错误,请告诉我。

我正在尝试在 Instagram 上制作一个有趣的机器人,其中一个功能是转到用户的页面,查看他们的关注者,然后开始关注该列表中的人。

这篇文章很相似,但是我从中提取的列表在滚动浏览每 12 个配置文件后会重新填充更多条目。

这是到目前为止的代码:

def follow_multiple(self, user):
        #navigate to user profile
        self.nav_user(user)
        time.sleep(3)

        #open followers window
        followers_button = self.driver.find_element_by_xpath("//a[contains(@href, '/{}/followers')]".format(user))
        followers_button.click()
        time.sleep(2)
        followers_popup = self.driver.find_element_by_xpath("/html/body/div[4]/div/div/div[2]")

        follower_popup_range = int(self.follower_amt(user))
        for i in range(int(follower_popup_range/11)):
            time.sleep(random.normalvariate(2, 0.3))
            f = 1
            while f<=12:
                
                try:
                    #try to click follow button
                    time.sleep(random.normalvariate(1.2, 0.2))   
                    lc = f + (i*11)
                    print('pressing' + str(lc) + '...')
                    self.driver.find_element_by_xpath("/html/body/div[4]/div/div/div[2]/ul/div/li[{}]/div/div[3]/button"
                        .format(lc)).click()
                    print('button ' + str(lc) + ' pressed')

                except:
                    print('button ' + str(lc) + 'failed')
                    time.sleep(random.normalvariate(0.2, 0.04))
                    #click cancel

                    try:
                        #attempt to click cancel on one xpath
                        self.driver.find_element_by_xpath("/html/body/div[5]/div/div/div/div[3]/button[2]").click()
                        print(str(lc) + ': Already following user')
                        f -= 1

                    except:
                        #other xpath for the same button
                        time.sleep(1)
                        self.driver.find_element_by_xpath("/html/body/div[5]/div/div/div/div[3]/button[2]").click()

                f += 1 
            #JS to scroll through list
            self.driver.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', followers_popup)
            time.sleep(2)

进入页面并打开关注框没有问题。外循环可以很好地滚动框。内部循环在打印后的第 12 个元素处死掉,说“按钮 12 失败”

内部循环应该通过并跟踪每个帐户(每个人口 12 个元素),并且 try 块用于处理单击已被跟踪的人,这会打开一个确认页面,它会点击取消。只是不确定为什么它在第 12 次和最后一次迭代结束时死掉,它给了我这个错误:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document 

但我不知道为什么,因为元素在那里。任何帮助是极大的赞赏。谢谢!

标签: pythonseleniumselenium-webdriverautomation

解决方案


推荐阅读