user3499450
user3499450

Reputation: 49

I want to find the xpath for the image

This is the html code

<div class="navBg">
<table id="topnav" class="navTable" cellspacing="0" cellpadding="0" style="-moz-user-        select: none; cursor: default;">
<tbody>
<tr>
<td class="logoCell" valign="top">
<td class="separator">
<td class="navItem relative" style="z-index: 99">
<td class="separator">
<td class="navItem relative">
<a class="content tasks" style="border-width: 0" href="/tasks/otasklist.do">
<div class="label" style="z-index:155; ">Tasks</div>
<img class="sizer" width="84" height="93" src="/img/default/pixel.gif? hash=1106906246"/>
<span class="bottomBorder">

I am trying to find the xpath for the image-->

src="/img/default/pixel.gif?hash=1106906246"

I have tried different combinations e:g

//table/tbody/tr/td[5][@class='navItem relative']/a/div[2]/img

I have written the following code too.

 WebDriverWait wait= new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Tasks")));

    driver.findElement(By.xpath("//table/tbody/tr/td[5][@class='navItem relative']/a/div[2]/img")).click();
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

It's identifying the element on web page by firepath but after running the script it's not clicking on the element and the console shows "No Such Element Exception".

Please answer in java lang only. Can somebody please help me out.???

Thx

Upvotes: 1

Views: 6304

Answers (2)

SiKing
SiKing

Reputation: 10329

I see you are using Selenium. The safest bet is to find the closest parent with an @id attribute, and work your way down from there. Try this: //table[@id='topnav']//img. As alecxe pointed out, depending on how unique the image is in this table, you may need to narrow the XPath down a little more. Something like //table[@id='topnav']//tr[1]//img, or even //table[@id='topnav']//td[contains(@class, 'navItem')]//img.

The XPath you posted will not work, as it has some problems compared to the sample HTML you posted:

  1. tbody may not appear in all browsers
  2. the qualifier [@class='navItem relative'] for the element td[5] is redundant (although this is not exactly a problem)
  3. div[2] does not exists, your HTML sample shows only one div

Upvotes: 1

alecxe
alecxe

Reputation: 473833

There are multiple ways to find the img tag. Depending on the uniqueness of the img tag attributes and it's location on the page.

Here's one way to find it, based on the Tasks div:

//table//div[text()='Tasks']/following-sibling::img

You can also rely on the td in which the img is located and check for the sizer class:

//table//td[contains(@class, 'navItem')]/img[@class='sizer']

And so on.

Upvotes: 0

Related Questions