Select Image in Selenium 2.9

2019-08-09 03:45发布

问题:

I'm trying to use RSpec to try and automate testing for post-maintenance weekends here where I'm interning at. I'm using Selenium WebDriver 2.9.0 to get a skelton going and then adding in personalized code. What I'm currently stuck on is trying to have the WebDriver click on an image that will then navigate to the correct HTML but I'm currently unable to do so. Here's what I have so far...

   it "can go to Ultratime" do
     @ie_driver.find_element(:link, "My Resources").click
     wait.until { @ie_driver.execute_script("return document.readyState;") == "complete" }
     sleep 3
     wait.until { @ie_driver.find_element(:link_text => "Login").displayed?}
       #test above line
       puts "found Ultratime"

     #this just finds the "Logout" button and clicks it
     @ie_driver.find_element(:name, "ee").click
   end

here's the html code pertaining to the said "button" for the site that I'm trying to navigate through:

<body id="ultratime-insidend" class="ultratime ultratime-insidend ">
<p id="ultratime">
<a class="single" href="#">
    <img alt="Ultratime" src="https://controller.nd.edu/stylesheets/images/logo2.gif"></img>
    Login
</a>

Any help would be greatly appreciated!

回答1:

Clicking on image works just like clicking on any other element. If you have problem locating image, give it id and use css selector i.e.

driver.find_element_by_css_selector("#yourimageid").click()

Edit: to switch focus to frame, use:

driver.switch_to.frame driver.find_element(..)

Any locator should work, if you can't set ID, like

drive.switch_to.frame driver.find_element( :xpath, "//iframe" )


回答2:

Clicking on image works just like clicking on any other element. If you have >problem locating image, give it id and use css selector i.e.

driver.find_element_by_css_selector("#yourimageid").click()

Edit: to switch focus to frame, use:

driver.switch_to.frame driver.find_element(..)

Any locator should work, if you can't set ID, like

drive.switch_to.frame driver.find_element( :xpath, "//iframe" )

Thank you Borsunho, after finding out that I needed to find the iframe first it made things much simpler. This was my end result:

 it "can go to Ultratime", focus: true do
   @ie_driver.find_element(:link, "My Resources").click
   @ie_driver.switch_to.frame(@ie_driver.find_element(:css, 'iframe[src="https://controller.nd.edu/ultratime/insidend/"]'))
   @ie_driver.find_element(:class,"single").click
 end