Get page element by title attribute - Selenium and Java

19,349

Solution 1

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.

Solution 2

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.
Share:
19,349
Vlad Vidac
Author by

Vlad Vidac

Ask me about functional programming and boardgames.

Updated on June 04, 2022

Comments

  • Vlad Vidac
    Vlad Vidac about 2 years

    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.