2017-08-02 122 views
-1

我得到IndexError:在遍歷html表時列表超出範圍,但我不確定是什麼導致它。下面是我編寫的用於迭代表格的函數。在每次迭代中,它會執行一次單擊(一個網頁框架)並下載文件(位於另一個框架中)。該表有20行。當網頁正確加載時,它工作正常。但是,一旦網頁掛起(即發生下載的幀),我的代碼就會進入超時異常並進入代碼頂部。之後,我在「employeeList [j] .click()」一行中得到了索引錯誤。在調試時,我發現前一行employeeList返回一個空列表。有人可以解釋是什麼導致這個問題。因爲一些線被跳過TimeoutExceptionSelenium Python- IndexError:在遍歷表中列出索引超出範圍

def candidate(): 

    for j in range(0,20): 

     driver.implicitly_wait(50) 
     employeeList=driver.find_elements_by_xpath("//td[7]/div/div[1]/a") 
     employeeList[j].click() 
     driver.switch_to_default_content() 
     driver.implicitly_wait(50) 
     driver.switch_to.frame("detail") 
     wait = WebDriverWait(driver,2) 

     try:     
      resume = wait.until(EC.presence_of_element_located((By.XPATH,"//div[@id='menubar']/div[1]/div/ul/li[2]/a/span"))) 
      driver.implicitly_wait(50) 
      resume.click() 
      download = wait.until(EC.presence_of_element_located((By.XPATH,'//a[@title="Download Resume"]'))) 

      driver.implicitly_wait(50) 
      download.click() 
      driver.implicitly_wait(50) 
      driver.switch_to.frame("RTFVIEWER_MS") 
      msword = wait.until(EC.presence_of_element_located((By.XPATH,"//div[@id='pagecontainer'>>]/div/a[2]/ul/li[2]"))) 
      driver.implicitly_wait(50)    
      msword.click() 
      print(j) 
     except TimeoutException as ex1: 
      print("Exception has been thrown"+str(ex1)) 
      print(j) 
      continue 

     driver.switch_to_default_content() 
     driver.switch_to.frame(0) 
+0

「在調試時,我發現前面的一行employeeList返回一個空列表,有人可以解釋是什麼導致了這個問題。」由於'driver.find_elements_by_xpath(「// td [7]/div/div [1]/a」)'返回一個空列表,我會假設問題出現在xpath中。 –

+0

嗨史蒂文,XPath工作正常,當它運行時沒有輸入except塊。只有當代碼在移動除了零件 – Vishnu

+0

之前返回到頂部時,纔會發生這種情況。在嘗試鎖定driver.switch_to.frame(「detail」)之前。在try塊中你可以使用driver.switch_to.frame(「RTFVIEWER_MS」)'。當你有超時異常時,你永遠不會得到切換到'RTFVIEWER_MS'的幀。處理異常時不要切換幀。我的猜測是你的xpath在幀RTFVIEWER_MS上工作,而不是幀「detail」。 –

回答

0

driver.find_elements_by_xpath("//td[7]/div/div[1]/a")失敗,因爲你是如何處理異常。

for循環的最後一行將驅動程序設置回xpath工作的原始框架driver.switch_to.frame(0)。當你有一個例外,你在except子句中做一個continue並跳過for循環的最後一行。或者不要continue或在你的except-clause中進行必要的清理。

相關問題