Reputation: 25
How can I iterate through or increment webelements as below:
example xpath:
.//*[@id='content']/div[5]/ul/li/ul/li[1]/a
.//*[@id='content']/div[5]/ul/li/ul/li[2]/a
Windows apps modules is the parent element. AMExchange2007 and AMHealth are elements at the same level. I would like to iterate through the elements at the same level.
Above provided xpath's are of elements at the same level. As requested adding HTML code:
<ul class="childpages-macro">
<li>
<a href="/display/DCM/Windows+Apps+Modules">Windows Apps Modules</a>
<ul class="childpages-macro">
<li>
<a href="/display/DCM/AM-Exchange2007">AM-Exchange2007</a>
<ul class="childpages-macro">
<li>
<a href="/display/DCM/Exchange2007+-+Hotfixes">Exchange2007 - Hotfixes</a>
</li>
<li>
<a href="/display/DCM/Exchange2007+-+Potential+Fixes+and+Diagnostic+Drops">Exchange2007 - Potential Fixes and Diagnostic Drops</a>
</li>
<li>
<a href="/display/DCM/Exchange-7.6">Exchange-7.6</a>
<ul class="childpages-macro">
<li>
<a href="/pages/viewpage.action?pageId=35359035">POC/Spike Sprint</a>
</li>
<li><li><li></ul></li><li></ul></li>
<li>
<a href="/display/DCM/AMHealth">AMHealth</a>
<ul class="childpages-macro">
<li>
<a href="/pages/viewpage.action?pageId=37127678">AM Health 8.2.0.2 (Hotfix)</a>
<ul class="childpages-macro">
<li>
<a href="/pages/viewpage.action?pageId=37129112">Sprint1 AC/AT's</a>
<ul class="childpages-macro">
<li><li><li><li></ul></li><li><li></ul></li>
<li>
<a href="/display/DCM/RCA+-+AMHealth">RCA - AMHealth</a>
</li></ul></li>
Sorry if the question is not very clear.
Upvotes: 2
Views: 538
Reputation: 52685
If I correctly understood the issue, you might need to use below code:
counter = 1
while len(driver.find_elements_by_xpath('//ul[@class="childpages-macro"]/li/a[count(./ancestor::ul[@class="childpages-macro"])=%d]' % counter)) > 0:
print("\n%d level links:" % counter)
for link in driver.find_elements_by_xpath('//ul[@class="childpages-macro"]/li/a[count(./ancestor::ul[@class="childpages-macro"])=%d]' % counter):
print(link.text)
counter += 1
The output is
1 level links:
Windows Apps Modules
2 level links:
AM-Exchange2007
AMHealth
3 level links:
Exchange2007 - Hotfixes
Exchange2007 - Potential Fixes and Diagnostic Drops
Exchange-7.6
AM Health 8.2.0.2 (Hotfix)
RCA - AMHealth
4 level links:
POC/Spike Sprint
Sprint1 AC/AT's
Upvotes: 1