Ruby Watir-尝试遍历cnn.com中的链接并单击每个链接 [英] Ruby Watir -- Trying to loop through links in cnn.com and click each one of them
问题描述
我创建了此方法来循环浏览网站中某个div中的链接.我的方法的目的是收集链接,然后将它们插入数组,然后单击其中的每个链接.
I have created this method to loop through the links in a certain div in the web site. My porpose of the method Is to collect the links insert them in an array then click each one of them.
require 'watir-webdriver'
require 'watir-webdriver/wait'
site = Watir::Browser.new :chrome
url = "http://www.cnn.com/"
site.goto url
box = Array.new
container = site.div(class: "column zn__column--idx-1")
wanted_links = container.links
box << wanted_links
wanted_links.each do |link|
link.click
site.goto url
site.div(id: "nav__plain-header").wait_until_present
end
site.close
到目前为止,看来我只能单击第一个链接,然后收到一条错误消息,指出以下内容:
So far it seems like I am only able to click on the first link then I get an error message stating this:
unable to locate element, using {:element=>#<Selenium::WebDriver::Element:0x634e0a5400fdfade id="0.06177683611003881-3">} (Watir::Exception::UnknownObjectException)
我对红宝石很陌生.感谢您的帮助.谢谢.
I am very new to ruby. I appreciate any help. Thank you.
推荐答案
问题在于,一旦导航到另一个页面,所有元素引用(即wanted_links
中的元素引用)就会失效.即使返回同一页面,Watir/Selenium也不知道它是同一页面,也不知道存储的元素在哪里.
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.
如果要离开,则需要先收集所有需要的数据.在这种情况下,您只需要href
值.
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
如果链接没有直接导航到页面(例如,单击时它们执行JavaScript),则您将需要收集足够的数据以便以后重新定位元素.用作定位器的内容将取决于已知的静态/唯一性.例如,我将假定链接文本是一个很好的定位器.
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
这篇关于Ruby Watir-尝试遍历cnn.com中的链接并单击每个链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!