【问题标题】:Resetting loop when going to next page转到下一页时重置循环
【发布时间】:2021-07-17 13:55:35
【问题描述】:

我有以下代码,用于下载文件:

followLoop = range(1, 49)
for x in followLoop:

    try:

        xpath = '//*[@id="ctl00_CPH_Main_ctl00_RadGridFacturen_ctl00__'
        xpath += str(x)
        xpath += '"]/td[10]/input'

        time.sleep(2)

        driver.find_element_by_xpath(xpath).click()

    except NoSuchElementException:
            print('exception')
            nextPage = driver.find_element_by_xpath('//*[@id="ctl00_CPH_Main_ctl00_RadGridFacturen_ctl00"]/tfoot/tr/td/table/tbody/tr/td/div[3]/input[1]')
            nextPage.click()
            continue

当它引发异常时,我希望在下一页重置循环范围。因此,当第 1 页引发异常时,我想从第 2 页开始以 1。

有谁知道我如何做到这一点?

【问题讨论】:

  • 请详细说明您的问题。

标签: python selenium loops


【解决方案1】:

你可以像这样使用while循环。

count = 1
while count < 49:
   try:
        xpath = '//*[@id="ctl00_CPH_Main_ctl00_RadGridFacturen_ctl00__' + str(x) + '"]/td[10]/input'
        time.sleep(2)
        driver.find_element_by_xpath(xpath).click()

        
   except NoSuchElementException:
        print('exception')
        nextPage = driver.find_element_by_xpath('//*[@id="ctl00_CPH_Main_ctl00_RadGridFacturen_ctl00"]/tfoot/tr/td/table/tbody/tr/td/div[3]/input[1]')
        nextPage.click()
        count = 1

这行得通吗?

【讨论】:

    【解决方案2】:

    您似乎需要另一个计数器,而您对多个页面使用相同的计数器。例如,如果您在第 1 页上没有找到第 9 项,则转到第 2 页,然后查找第 10 项

    pages  = range(1, 49). # change to how many pages you want to look at
    
    for page in pages:
        
        for item in range(1, 49):
    
            try:
        
                xpath = f'//*[@id="ctl00_CPH_Main_ctl00_RadGridFacturen_ctl00__{item}"]/td[10]/input'
        
                time.sleep(2)
        
                driver.find_element_by_xpath(xpath).click()
        
            except NoSuchElementException:
                    print('exception')
                    nextPage = driver.find_element_by_xpath('//*[@id="ctl00_CPH_Main_ctl00_RadGridFacturen_ctl00"]/tfoot/tr/td/table/tbody/tr/td/div[3]/input[1]')
                    nextPage.click()
                    break
    

    【讨论】:

      猜你喜欢
      • 2021-08-27
      • 1970-01-01
      • 2014-10-05
      • 2023-01-02
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多