迭代/增加webelements

时间:2017-04-16 12:07:00

标签: python-2.7 xpath selenium-webdriver

如何迭代或增加webelements,如下所示:

示例xpath:

.//*[@id='content']/div[5]/ul/li/ul/li[1]/a

.//*[@id='content']/div[5]/ul/li/ul/li[2]/a

Windows应用商店模块是父元素。 AMExchange2007和AMHealth是同一级别的元素。我想在同一级别迭代元素。

上面提供的xpath是同一级别的元素。 根据要求添加HTML代码:

<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>

很抱歉,如果问题不是很清楚。

1 个答案:

答案 0 :(得分:1)

如果我正确理解了这个问题,您可能需要使用以下代码:

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 

输出

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