I have the following question from an interview: Write an xpath to access the hotels link by traversing from flights link:
i have highlighted the flights link in web browsertool. but how to do after that i am not sure
CodePudding user response:
for this HTML:
<ul >
<li data-cy="menu_Flights" >
<a href="https://www.makemytrip.com/flights/" >
<span ></span>
<span >
<!-- --> <!-- -->Flights
</span>
</a>
</li>
<li data-cy="menu_Hotels" >
<a href="https://www.makemytrip.com/hotels/" >
<span ></span>
<span >
<!-- --> <!-- -->Hotels
</span>
</a>
</li>
<li data-cy="menu_Homestays" >
<a href="https://www.makemytrip.com/homestays/" >
<span ></span>
<span >
<!-- --> <!-- -->Homestays
</span>
</a>
</li>
<li data-cy="menu_Holidays" >
<a href="https://www.makemytrip.com/holidays-india/" >
<span ></span>
<span >
<!-- --> <!-- -->Holiday Packages
</span>
</a>
</li>
<li data-cy="menu_Trains" >
<a href="https://www.makemytrip.com/railways/" >
<span ></span>
<span >
<!-- --> <!-- -->Trains
</span>
</a>
</li>
<li data-cy="menu_Buses" >
<a href="https://www.makemytrip.com/bus-tickets/" >
<span ></span>
<span >
<!-- --> <!-- -->Buses
</span>
</a>
</li>
<li data-cy="menu_Cabs" >
<a href="https://www.makemytrip.com/cabs/" >
<span ></span>
<span >
<!-- --> <!-- -->Cabs
</span>
</a>
</li>
<li data-cy="menu_Visa" >
<a href="https://www.makemytrip.com/visa/" >
<span ></span>
<span >
<!-- --> <!-- -->Visa
</span>
</a>
</li>
<li data-cy="menu_Charters" >
<a href="https://www.makemytrip.com/charter-flights/" >
<span ></span>
<span >
<!-- --> <!-- -->Charter Flights
</span>
</a>
</li>
<li data-cy="menu_Activities" >
<a href="https://www.makemytrip.com/activities/" >
<span ></span>
<span >
<!-- --> <!-- -->Activities
</span>
</a>
</li>
</ul>
A simple xpath to access the hotels link
by traversing from flights link
:
//a[contains(@href,'/flights/')]/../following-sibling::li
Explanation:
//a[contains(@href,'/flights/')]
is to target flights
and then go step up in DOM by using /..
and the looking for following-sibling
which is li