2

我正在尝试使用 Selenium 和 Ruby 自动更新工作联系人。我有一个与网页上的姓名相匹配的联系人姓名的 CSV。该网页一次仅显示 50 个联系人,并带有“下一步”按钮以继续。当我的 ruby​​ 脚本到达一个名称(即"Barbara"第 51 个联系人)时,脚本无法找到该元素,因为"Barbara"它不在第一页上,而是在下一页上。

当 WebDriver 找不到页面元素时,它会引发错误:

失败:1) RackspaceAutomation test_rackspace_automation 失败/错误:@driver.find_element(:link, row[0]).click Selenium::WebDriver::Error:NoSuchElementError: Unable to locate element: {"method":"link text", “选择器:”:“芭芭拉”}

并退出程序。相反,当它没有找到给定的名称时,我希望@driver.find_element(:id, "Next").click执行该行并再次搜索该名称。

我做了一些更改来处理错误。到目前为止的代码:

CSV.foreach('C:\Users\James\SeleniumTests\WebbContactsFullCVS.cvs') 做 |row|

  begin
    @driver.find_element(:link, row[0]).click
    @driver.find_element(:link, "Contact Information").click
    # ERROR: Caught exception [ReferenceError: selectLocator is not defined]
    a=@driver.find_element(:id,'PhoneNumberType')
    options=a.find_elements(:tag_name=>"option")
    options.each do |g|
      if g.text == "Mobile"
        g.click
        break
      end
    end
    @driver.find_element(:id, "MobilePhone").send_keys row[1]
    # ERROR: Caught exception [ReferenceError: selectLocator is not defined]
    options.each do |g|
      if g.text == "Fax"
        g.click
        break
      end
    end
    @driver.find_element(:id, "Fax").send_keys row[2]
    @driver.find_element(:css, "button.primary").click
  rescue NoSuchElementError
    @driver.find_element(:id, "Next").click
    retry
  end
end

得到错误:

失败: 1) RackspaceAutomation test_rackspace_automation 失败/错误:rescue NoSuchElementError NameError: uninitialized constant NoSuchElementError # ./RackspaceAutomation.rb:57:in 'rescue in block (3 levels) in ' # ./RackspaceAutomation.rb:35:in 'block ( '# ./RackspaceAutomation.rb:35:in '块(2 级)中的 3 级)'

, Ruby 新手,所以不确定如何/在哪里初始化它。任何帮助都会很棒!

4

1 回答 1

3
class NoSuchElementError < Exception
end

names = %w[ a b c ]
on_page = %w[ a b ]

names.each do |name|
  begin
    raise NoSuchElementError if not on_page.include? name
  rescue NoSuchElementError
    puts "rescuing: #{name}"
    on_page = %w[c d]
    retry
  end
end

--output:--
rescuing: c

所以你可以做这样的事情:

names.each do |name|
  begin
    #error throwing code here
  rescue NoSuchElementError
    @driver.find_element(:id, "Next").click
    retry
  end
end
于 2013-09-05T05:00:42.097 回答