【问题标题】:How to recover when Selenium cannot find elementSelenium 找不到元素时如何恢复
【发布时间】:2013-09-05 15:12:09
【问题描述】:

我正在尝试使用 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: 无法定位元素:{"method":"link text","selector:":"Barbara"}

并退出程序。相反,当它没有找到给定的名称时,我希望执行 @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 失败/错误:救援 NoSuchElementError 名称错误: 未初始化的常量 NoSuchElementError # ./RackspaceAutomation.rb:57:in 'rescue in block (3 levels) in ' # ./RackspaceAutomation.rb:35:in 'block (3 levels) in ' # ./RackspaceAutomation.rb:35:in 'block (2 levels) in '

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

【问题讨论】:

    标签: ruby if-statement selenium webdriver


    【解决方案1】:
    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
    

    【讨论】:

    • 1) 是的,我的第一个代码示例模拟了您正在尝试做的事情,并且我显示了一些输出,因此您可以知道代码做了什么。 2) 您的错误抛出代码与您的正常运行代码相同。将该代码放在第二个代码示例中的注释位置
    • 当您的程序因 NoSuchElementError 而退出时,错误消息应说明程序中的哪一行引发了错误。那是你的错误抛出代码
    • 如果 click() 没有返回页面,则需要跳过重试。
    • 所以我运行它并得到与以前相同的错误消息。是否有某种包含或“要求”我需要处理错误?
    • 试试rescue Selenium::WebDriver::Error::NoSuchElementError
    猜你喜欢
    • 2020-06-07
    • 1970-01-01
    • 2019-01-02
    • 2021-03-14
    • 1970-01-01
    相关资源
    最近更新 更多