Python 2.7 使用Python中的Seleneium webdriver在循环中单击具有相同链接文本的链接

Python 2.7 使用Python中的Seleneium webdriver在循环中单击具有相同链接文本的链接,python-2.7,selenium-webdriver,web-scraping,Python 2.7,Selenium Webdriver,Web Scraping,我使用以下代码滚动页面并跟踪quora上的用户(页面链接:),向下滚动后会加载一定数量的用户,我使用以下代码: # find all the follow buttons that are loaded button = driver.find_elements_by_xpath("//a[contains(text(), 'Follow')]") #number of users loaded no_of_followers = len(button) #execute the code

我使用以下代码滚动页面并跟踪quora上的用户(页面链接:),向下滚动后会加载一定数量的用户,我使用以下代码:

# find all the follow buttons that are loaded
button = driver.find_elements_by_xpath("//a[contains(text(), 'Follow')]")

#number of users loaded
no_of_followers = len(button)

#execute the code till all the users are followed
while(no_of_followers > 0):

    count = 0
    #follow all the users loaded by clicking follow button in a loop 
    while(count < no_of_followers):

        button[count].click()
        time.sleep(30)
        print count
        count = count + 1

    #scroll down        
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(30)'
    #find newly loaded users
    button = driver.find_elements_by_xpath("//a[contains(text(), 'Follow')]")
    time.sleep(30)
    #tracking no of users left unfollowed
    no_of_followers = len(button)
#查找加载的以下所有按钮
button=driver.find_elements_by_xpath(//a[contains(text(),'Follow')]))
#加载的用户数
无追随者数量=len(按钮)
#执行代码,直到所有用户都被跟踪
而(没有追随者>0的追随者):
计数=0
#通过单击循环中的“跟踪”按钮,跟踪加载的所有用户
而(计数<无追随者):
按钮[计数]。单击()
时间。睡眠(30)
打印计数
计数=计数+1
#向下滚动
执行脚本(“window.scrollTo(0,document.body.scrollHeight);”)
时间。睡眠(30)'
#查找新加载的用户
button=driver.find_elements_by_xpath(//a[contains(text(),'Follow')]))
时间。睡眠(30)
#跟踪未跟踪的用户数
无追随者数量=len(按钮)
我遇到以下错误:

StaleElementReferenceException:消息:u'Element不再附加到DOM';堆栈跟踪:


编辑1:我尝试使用
通过链接文本查找元素,但函数的输出对象显然不是可以迭代的链接列表。

可能的问题是@button[count]。单击()。 我建议您使用for循环而不是while,并使用迭代器增加它

做点像

//你基本上需要一直点击第一个项目。迭代器应该只控制迭代次数

 Driver.FindElement(By.Xpath("Your Xpath")).Click();

抱歉,我不是python方面的专家。

实际上,我正在单击页面上的所有用户,而不仅仅是第一个用户。我使用no_of_followers变量来跟踪加载的用户数。请解释一下循环的区别好吗?好吧,我想你也可以使用while循环,但不能使用按钮[count]。单击()我还尝试了“driver.find_elements_by_xpath(//a[contains(text(),'Follow')][count]”。单击()”。即使这样做不太好,我想你也可以使用while循环,但不能使用按钮[count]。click()。这背后的原因是,只要使用button=driver向下滚动找到的元素,就可以使用xpath(“a[contains(text(),'Follow')]”查找元素从DOM分离,并返回staleelement ref异常。为了避免您需要动态查找元素。并且,您始终希望单击第一项的原因是,只要您单击“跟随文本”更改为“跟随”,并且您希望单击页面上具有跟随文本的第一项。底线是,使用while或for循环控制滚动,并使用适当的选择器单击“第一步”按钮