如何限制 Watir 收集的按钮数量?

How to limit the amount of buttons Watir collects?

我正在收集推特的关注按钮。如何将按钮限制为仅 30 个按钮而不是页面上的所有按钮?

    #Collect the "Follow" buttons
    browser.spans(:class => ['user-actions-follow-button js-follow-btn follow-button']).each do |b|

        #Click them! One by one.
        b.click

        # Generate random sleep period
        r = Random.rand(4...7)

        #Sleep so not to appear like a bot.
        sleep(r)
        # end
    end

使用#shift方法

browser.spans(:class => ['user-actions-follow-button js-follow-btn follow-button'])
    .to_a
    .shift(30)
    .each do |b|

  b.click

end

元素集合包括 Enumerable,因此您可以使用 #take:

browser.spans(:class => ['user-actions-follow-button js-follow-btn follow-button']).take(30).each do |b|
    b.click
end