2016-07-01 3 views
1

저는 tkinter 모듈을 사용하여 Python으로 GUI 기반 프로젝트를 만들고 있습니다. 예를 들어 Beautiful Soup을 사용하는 SPOJ와 같은 온라인 판사로부터 기본 데이터를 가져옵니다. 나는 파이썬에서 초보자이기 때문에 필자가 작성한 대부분의 것들은 인터넷의 기본 튜토리얼과 함께있다. 그러나 코드의 특정 부분에 대해서는 완전히 갇혀 있습니다. 나는이 부분을 테스트 한 후 파이썬 submissions.pyIndexError : BeautifulSoup를 사용하는 함수에서 인덱스가 범위를 벗어남

그것을 실행할 때

import sys 
import urllib.request 
from bs4 import BeautifulSoup 
import re 

userName = 'xilinx' 
spojUrl = 'http://www.spoj.com/users/'+userName 

with urllib.request.urlopen(spojUrl) as x: 
    html = x.read() 
soup = BeautifulSoup(html, 'html.parser') 
# li - list of successful submissions 
li = soup.find_all('table', class_='table table-condensed')[0].find_all('td') 
listOfSolvedProblemCodes = [] 
    for submission in li: 
     problemCode = submission.get_text() 
     if problemCode: 
      listOfSolvedProblemCodes.append(problemCode) 
print (userName+ ' has solved',len(listOfSolvedProblemCodes),'problems on Spoj.') 

코드의이 부분은 잘 작동, 나는 문제가 발생하는 더 큰 코드에 통합하려고합니다.

frame.py에서 :

def compStats(): 
    if ch == "SPOJ": 
     stats.show(ch, userName) 

B2 = tkinter.Button(root, text="My Statistics", command=compStats) 
B2.place(anchor = W, x = 30, y = 220, width=200) 

stats.py에서 :

def show(ch, userName): 

    if ch == 'SPOJ': 

     spojUrl = 'http://www.spoj.com/users/'+userName 

     with urllib.request.urlopen(spojUrl) as x: 
      html = x.read() 
     soup = BeautifulSoup(html, 'html.parser') 
     li = soup.find_all('table', class_='table table-condensed')[0].find_all('td') 
     listOfSolvedProblemCodes = [] 
     for submission in li: 
      problemCode = submission.get_text() 
      if problemCode: 
       listOfSolvedProblemCodes.append(problemCode) 


    # then collect more information from soup and print it through labels in another window 

    det = tkinter.Tk() 
    det.title("Statistics") 
    det.geometry("800x600") 

그러나 IndexError의 문제가 줄을 stats.py에서 발생하는 I는 관련 코드의 섹션 여기에 포함하고 :

li = soup.find_all('table', class_='table table-condensed')[0].find_all('td') 

Exception in Tkinter callback

Traceback (most recent call last):

File "C:\Users\Aa\AppData\Local\Programs\Python\Python35-32\lib\tkinter__init .py", line 1550, in __call

return self.func(*args)

File "frame.py", line 34, in compStats

stats.show(ch, userName)

File "C:\Users\Aa\AppData\Local\Programs\Python\Python35-32\stats.py", line 17, in show

li = soup.find_all('table', class_='table table-condensed')[0].find_all('td')

IndexError: list index out of range

코드가 여기에서 작동하지 않는 이유를 이해할 수 없습니다. 도와주세요!

답변

3

디버깅의 첫 번째 단계는 오류가 발생하는 복잡한 선을 취해 더 간단하게 만드는 것입니다. 그런 다음 중간 값을 검사하여 코드에 대한 가정이 사실인지 확인하십시오. 이 경우 soup.find_all('table', ...)이 실제로 뭔가를 찾고 있다고 가정합니다.

예를 들어, 다음을 변경 :

li = soup.find_all('table', class_='table table-condensed')[0].find_all('td') 

을 여기에 :

tables = soup.find_all('table', class_='table table-condensed') 
li = tables[0].find_all('td') 

다음, tmp을 조사하기 인쇄 문을 추가 :

print("tables is", tables) 

당신은 tables는 것을 발견 할 것이다 빈, 그래서 당신이 할 때하려고하면 tables[0]어요 인덱스 0이 범위를 벗어 났으므로

+0

나는 당신이 제안한 접근 방식을 시도하고 같은 문제가 발견되어 그 테이블은 비어있다. 하지만 html 파일에서 테이블이 비어서는 안된다는 것을 알고 있습니다. 이 코드를 별도로 실행하면 동일한 문제가 확인되어 3138 번 문제를 해결할 수 있습니다.이 경우 해결 된 문제의 수는 td 태그의 수입니다. 그러므로 혼란. 같은 코드가 다르게 작동하는 이유는 무엇입니까? – Neha

+0

같은 이유로 나는 별도로 실행하는 전체 코드를 입력하고 대답을 얻습니다. 그래서 다른 사람들도 그것을 실행하고 점검 할 수 있습니다. 하지만 일단 함수에 넣으면 범위를 벗어나는 인덱스의 오류가 표시됩니다. – Neha

+0

@Neha : 다른 출력을 얻는다면 아마도 다른 입력을 제공 할 것입니다. 모든 경우에 똑같은 입력을한다는 가정을 확인 했습니까? 동일한 변수 이름이 아니라 변수의 실제 내용입니까? 어쩌면'username'은 당신이 생각하는 것과 다를 수 있습니다. –