Reputation: 998
I'm trying to get the image which has the word "Collector" in its title and click on it. This is the html code for the image and its link:
<a href="javascript:*command*" title="Level III: KPI Collector RYG of D D/Testing - SYS">
<img src="*unusable link because it's only valid for the specific page*" title="Level III: KPI Collector RYG of D D/Testing - SYS">
The <a>
and <img>
tags are nested in a table cell and some divs. I didn't write the html code so don't yell at me if it's ugly :p
Here is the java code where I try to do it:
WebElement trafficLight = driver.findElement(By.xpath("//img[contains(@title,'Collector')]"));
trafficLight.click();
The error I get is:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//img[contains(@title,'Collector')]"}
I'm pretty sure the xpath is ok so I don't think that's the issue.
Upvotes: 3
Views: 22200
Reputation: 473
Please try this. It will resolve your problem.
WebElement frameSwitch = driver.findElement(By.xpath("Give iframe Xpath location"));
driver.switchTo().frame(frameSwitch); //Switch control to iframe.
//Perform your steps (I.e Click on Image)
driver.findElement(By.xpath("//img[contains(@title,'Collector')]")).click();
driver.switchTo().defaultContent(); //Come out of iframe.
Upvotes: 3
Reputation: 472
As the img
WebElement is within a frame, you will need to switch focus to that frame before you perform any action on that WebElement. You can do that using WebDriver's switchTo()
method like so:
driver.switchTo().frame(frameLocator);
The frame locator can be either its (zero-based) index, name or id attribute, or a previously located WebElement.
Once you have switched focus to the required frame, you should then be able to interact with the WebElement using the same code in your initial post.
Upvotes: 3