【问题标题】:Clicking the links having same link text in a loop using Seleneium webdriver in Python在 Python 中使用 Selenium webdriver 在循环中单击具有相同链接文本的链接
【发布时间】:2014-09-18 14:43:18
【问题描述】:

我正在使用以下代码滚动页面并关注 quora 上的用户(链接到页面:http://www.quora.com/Kevin-Rose/followers),向下滚动后加载了一定数量的用户,我使用下面给出的代码:

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

我收到以下错误:

StaleElementReferenceException: Message: u'Element is no longer attach to the DOM' ;堆栈跟踪:

编辑1:我尝试使用find_element_by_link _text,但显然该函数的输出对象不是可以迭代的链接列表。

【问题讨论】:

    标签: python-2.7 selenium-webdriver web-scraping


    【解决方案1】:

    可能的问题是@button[count].click()。 我建议您使用 for 循环而不是 while 并使用迭代器对其进行递增。

    做类似的事情

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

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

    抱歉,不是python专家。

    【讨论】:

    • 实际上,我点击的是页面上的所有用户,而不仅仅是第一个用户。我正在使用 no_of_followers 变量来跟踪已加载的用户数量。请您解释一下 for 循环会有什么不同?
    • 好吧,我猜你应该也可以使用 while 循环,但不是 button[count].click()
    • 我也试过 "driver.find_elements_by_xpath("//a[contains(text(), 'Follow')][count]").click()" ..即使那不起作用
    • 好吧,我想你应该也可以使用 while 循环,但不能使用 button[count].click()。这背后的原因是,一旦您向下滚动使用 button = driver.find_elements_by_xpath("//a[contains(text(), 'Follow')]") 找到的元素,就会从 DOM 中分离出来并返回 staleelement ref 异常.为了避免这种情况,您需要动态查找元素。而且,您总是想单击第一项的原因是,一旦您单击关注文本就会更改为关注,并且您想单击页面上具有关注文本的第一项。
    • 底线是,使用 while 或 for 循环来控制滚动,并使用适当的选择器点击第一个关注按钮
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多