Alex Alex - 4 months ago 8
HTML Question

Looking for correct Locator for Selenium testing

So I'm working on this project and I need to find the correct locator for Selenium testing. I've tried a bunch of different combinations and I can't find the right one to click this link. Everything I try throws a No Such Element exception.

I need to click the first link in the unordered list. Here is the HTML



<main id="content" role="main">
<nav id="product-list" role="navigation">
<ul>
<li id="firstTile">
<a class="productLink" href="***LINK***" target="_top">
<img src="***image ref***">
<p>
<span class="productName" title="First Tile"></span>
<br>
<small>This is the text for the first tile</small>
</p>
</a>
<div class="item-footer cf">
<hr>
</li>
<li id="secondTile">
<li id="thirdTile">
<li id="fourthTile" class="coming-soon">
</ul>
</nav>
<div class="extra-links cf">
</main>





Here is my Java:

Test class

// All imports

public class Test {

private Home home;
//All other variables

@Before
public void setup() {
driver = new FirefoxDriver();
}

@Test
public void clickFirstTile() {
home = new Home(driver);
home.clickFirstTile();
}

@After
public void tearDown() {
driver.quit();
}
}


And also my Home Page Object class:

public class Home {

private WebDriver driver;
By firstTileBtnLocator = By.id("firstTile");

public Home(WebDriver driver) {
this.driver = driver;
// I've replaced my site with this fake url. The real site url works.
driver.navigate().to("http://myfakesite.com");
}

public void clickFirstTile() {
driver.findElement(firstTileBtnLocator).click();
}
}

Answer

I would suggest a different locator

By firstTileBtnLocator = By.cssSelector("#firstTile a.product-link");

I'm guessing there are a number of

<a class="productLink" href="***LINK***" target="_top">

elements on the page. The CSS Selector above will target only the one under <li id="firstTile">.


After seeing the site, the problem is that the element is inside an IFRAME and there was a mistake in the HTML you posted (incorrect id). I've tried the code below and it works.

driver.get("http://www.wolframcloud.com/");
driver.switchTo().frame(0);
driver.findElement(By.cssSelector("#wdp-tile a.product-link")).click();
driver.switchTo().defaultContent();

You would edit a couple places in your classes.

By firstTileBtnLocator = By.cssSelector("#wdp-tile a.product-link");

and

public void clickFirstTile() {
    driver.switchTo().frame(0);
    driver.findElement(firstTileBtnLocator).click();
}

I think that should take care of it.

More info on dealing with IFRAMEs.

How to switch between frames in Selenium WebDriver using Java