Himadri
Himadri

Reputation: 150

Webdriver/Xpath/Java: Crawl DOM to click on 'Element with No Unique Identifier'

I am trying to find and click 'Available' seats from a Travel website Seat Layout. Challenge is, the available Seat has no Unique Identifier whereas 'Blocked' (already booked) seat has one in the form of 'title' (Please refer HTML). How we make WebDriver skip any blocked seat and click any 'Available' seat on any random occurrence of seat layout (Pic)??

SeatLayout

HTML shows structure of 2 Blocked Seats (L2 , L4) and one available seat in between (L3)

    <div style="max-width:695px;">
<div class="GXXXXXXX" style="display: none;" aria-hidden="true">
<div class="GXXXXXXX">
<div class="GXXXXXXX"> </div>
<div class="GXXXXXXX">
<table>
<colgroup>
<tbody>
<tr>
<tr>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
Blocked Seat
<div class="GDXXXXXX GDXXXXX0" style="overflow:hidden;position:static;margin: 0 5px 5px 0;" title="Seat Name: L2 | Fare: Rs. 300.0">L2</div>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
Available Seat
<div class="GXXXXXX GXXXXXX0" style="overflow:hidden;position:static;margin: 0 5px 5px 0;">L3</div>
</td>
</tr>
<tr>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
<td>
Blocked Seat
<div class="GXXXXXX GXXXXXXX" style="overflow:hidden;position:static;margin: 0 5px 5px 0;" title="Seat Name: L4 | Fare: Rs. 300.0">L4</div>
</td>
</tr>
<tr>
</tbody>
</table>
</div>

Upvotes: 0

Views: 379

Answers (1)

Purus
Purus

Reputation: 5799

This is the logic. See if the DIV has title attribute. If it does not have the seat is available. Change the logic as per your need.

List<WebElement> seats = driver.findElements(By.cssSelector("div.GXXXXXX.GXXXXXXX"));

for (WebElement seat : seats) {
   if(seat.getAttribute("title") != null){
        System.out.println("Seat is not available");
   }else{
        System.out.println("Seat is available");
        seat.click(); // break the loop if you wish
   }                    
}

Upvotes: 1

Related Questions