【问题标题】:Ruby Watir -- Trying to loop through links in cnn.com and click each one of themRuby Watir -- 尝试遍历 cnn.com 中的链接并单击其中的每一个
【发布时间】:2016-12-19 19:57:41
【问题描述】:

我创建了这个方法来循环访问网站中某个 div 中的链接。我的方法是收集链接,将它们插入到一个数组中,然后单击其中的每一个。

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

到目前为止,我似乎只能点击第一个链接,然后我收到一条错误消息,说明:

  unable to locate element, using {:element=>#<Selenium::WebDriver::Element:0x634e0a5400fdfade id="0.06177683611003881-3">} (Watir::Exception::UnknownObjectException)

我对红宝石很陌生。我很感激任何帮助。谢谢。

【问题讨论】:

    标签: ruby automation watir


    【解决方案1】:

    问题在于,一旦您导航到另一个页面,所有元素引用(即wanted_links 中的那些)都会变得陈旧。即使返回到同一个页面,Watir/Selenium 也不知道它是同一个页面,也不知道存储的元素在哪里。

    如果您要离开,您需要先收集所有需要的数据。在这种情况下,您只需要 href 值。

    # 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),您将需要收集足够的数据以便稍后重新定位元素。您用作定位器的内容取决于已知的静态/唯一内容。例如,我假设链接文本是一个很好的定位器。

    # 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
    

    【讨论】:

    • 太棒了。感谢您提供信息@Justin Ko
    • 嘿贾斯汀我也试过这个方法,但我仍然收到一个错误说“未定义的方法‘点击’”。这是下一条评论中的方法。谢谢
    • '需要 'watir-webdriver' 需要 'watir-webdriver/wait' 站点 = Watir::Browser.new :chrome url = "cnn.com" site.goto url 容器 = site.div( class: "column zn__column--idx-1") Wanted_links = container.links.collect(&:text) puts Wanted_links Want_links[1].click'
    • 您收到该错误是因为您尝试在(链接文本的)字符串而不是 Watir::Anchor 元素上调用 click。您想达到什么目的(因为您刚刚提供的代码似乎与原始代码和答案大不相同)?
    • 我在想我可以得到所有存储在想要的链接中的链接。然后我可以单击每个并返回主页。示例 Wanted_links[1].click 然后是 site.back 并再次 Wanted_links[2].click 等等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 2020-10-02
    相关资源
    最近更新 更多