2017-08-02 124 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中进行必要的清理。

相关问题