简体   繁体   English

在没有 for 循环的情况下增加 i

[英]Incrementing i without for loop

I have this code:我有这个代码:

for i in range(1, 7):

    browser.find_element_by_xpath('//*[@id = "dtree0"]/div[' + str(i) +']/ a[2]').click()

I have some outer loop like this:我有一些这样的外循环:

elements = browser.find_elements_by_xpath('//*[@id="dtree0"]/div/a')

names=[]

for elem in elements:

    names.append(elem.text)
    print(names)
#
# #     # click elements in the target level (names)
    for i in range(0, len(elements)):
        elements = browser.find_elements_by_xpath ('//*[@id="dtree0"]/div/a')
        elem = elements[i]
#     #         # only click the elements in the names list (this level)
        if elem.text in names:
            names.remove(elem.text)
            try:
                elem.click()
            except WebDriverException:
                 pass  # ignore if elem is not clickable
        browser.find_elements_by_id("stree2").click()
        browser.find_element_by_xpath ('/html/body/center[2]/form/table[1]/tbody/tr/td[3]/table/tbody/tr[5]/td[1]/a[1]/img').click ()

        browser.find_element_by_xpath ('/html/body/center[2]/form/table[2]/tbody/tr/td[4]/input').click()
        browser.find_element_by_xpath ('/html/body/center/form/table[2]/tbody/tr/td[5]/a').click ()
        sleep (5)

I want to fit the upper code into the bottom code somewhere without the for loop.我想在没有 for 循环的情况下将上部代码放入底部代码中。 So the basic idea is to write the first loop without the for loop.所以基本思路是写第一个循环而不用for循环。 The second block of code (outer loop) is just for context.第二个代码块(外循环)仅用于上下文。

Not sure the logic why you are storing the names and then removing them from names[] .不确定为什么要存储名称然后从names[]删除它们的逻辑。 But, try the below which should answer your question.但是,请尝试以下应该回答您的问题。

elements = browser.find_elements_by_xpath('//*[@id="dtree0"]/div/a')
names=[]
for elem in elements:
    names.append(elem.text)
    print(names)
# click elements in the target level (names)
for i in range(0, len(elements)):
    elem = browser.find_elements_by_xpath('//*[@id="dtree0"]/div/a')[i]
# only click the elements in the names list (this level)
    if elem.text in names:
        names.remove(elem.text)
        try:
            elem.click()
        except WebDriverException:
             pass  # ignore if elem is not clickable
    browser.find_element_by_id("stree2").click()
    browser.find_element_by_xpath ('/html/body/center[2]/form/table[1]/tbody/tr/td[3]/table/tbody/tr[5]/td[1]/a[1]/img').click ()

    browser.find_element_by_xpath ('/html/body/center[2]/form/table[2]/tbody/tr/td[4]/input').click()
    browser.find_element_by_xpath ('/html/body/center/form/table[2]/tbody/tr/td[5]/a').click ()
    sleep (5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM