Ruby Watir — Trying to loop through links in cnn.com and click each one of them

岁酱吖の 提交于 2019-12-06 14:13:10

The problem is that once you navigate to another page, all of the element references (ie those in wanted_links) become stale. Even if you return to the same page, Watir/Selenium does not know it is the same page and does not know where the stored elements are.

If you are going to navigate away, you need to collect all of the data you need first. In this case, you just need the href values.

# Collect the href of each link
wanted_links = container.links.map(&:href)

# You have each page URL, so you can navigate directly without returning to the homepage
wanted_links.each do |link|
  site.goto url
end

In the event that the links do not directly navigate to a page (eg they execute JavaScript when clicked), you will need to collect enough data to re-locate the elements later. What you use as the locator will depend on what is known to be static/unique. As an example, I will assume that the link text is a good locator.

# Collect the text of each link
wanted_links = container.links.map(&:text)

# Iterate through the links
wanted_links.each do |link_text|
  container = site.div(class: "column zn__column--idx-1")
  container.link(text: link_text).click

  site.back
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!