findElements(By.xpath()) finds elements only when given full path

Viewed 203

I've a page containing the path

/html/body/div[5]/div[2]/div[2]/div/div[2]/form/div/div[2]/div/div/div[6]/div

of which the bottom-most div resolves to

<div id="tab-topTabs--Lumber">
  <div>
    <ul>
      <li>
        <a href="#tab-topTabs--Lumber-0">2x4</a>
      </li>
      <li>
        <a href="#tab-topTabs--Lumber-1">4x4</a>
      </li>
      <li>
        <a href="#tab-topTabs--Lumber-2">4x6</a>
      </li>
    </ul>
  </div>
</div>

both of these will find the right element

WebElement divTopTabLumber_1 = m.getDriver().findElement(By.xpath("/html/body/div[5]/div[2]/div[2]/div/div[2]/form/div/div[2]/div/div/div[6]/div"));
WebElement divTopTabLumber_2 = m.getDriver().findElement(By.id("tab-topTabs--Lumber"));

Problem - calling using the full path grabs the correct three list elements under the deepest div:

List<WebElement> list_lumber_0 = m.getDriver().findElements(By.xpath("/html/body/div[5]/div[2]/div[2]/div/div[2]/form/div/div[2]/div/div/div[6]/div/div/ul/li"));

but these do not:

List<WebElement> list_lumber_1 = divTopTabLumber_1.findElements(By.xpath("//div//ul//li"));
List<WebElement> list_lumber_2 = divTopTabLumber_2.findElements(By.xpath("//div//ul//li"));

reporting 206 elements instead of the expected 3.

Any suggestions/critiques/solutions would be greatly appreciated.

TIA,

Still-learning Steve

1 Answers

I would believe that this id

tab-topTabs--Lumber

is unique in HTMLDOM.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL + F -> then paste the //div[@id='tab-topTabs--Lumber'] and see, if your desired element is getting highlighted with 1/1 matching node.

if it is then use the below code to locate all 3 li nodes:

List<WebElement> list_lumber_2 = divTopTabLumber_2.findElements(By.xpath(".//descendant::li"));
Related