【发布时间】:2016-11-03 19:07:32
【问题描述】:
我正在使用模块 tkinter 在 Python 中制作一个基于 GUI 的项目。它从在线评委那里获取基本数据,例如,使用 Beautiful Soup 的 SPOJ。我是 Python 的新手,所以我写的大部分内容都是来自互联网的基本教程。然而,对于一段特定的代码,我完全被困住了。
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.')
这部分代码在我使用 python submits.py 运行时运行良好
在测试这部分之后,我尝试将其合并到出现问题的较大代码中。我在这里包括代码的相关部分:
在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这一行:
li = soup.find_all('table', class_='table table-condensed')[0].find_all('td')
Tkinter 回调异常
Traceback(最近一次调用最后一次):
文件 "C:\Users\Aa\AppData\Local\Programs\Python\Python35-32\lib\tkinter__init .py",第 1550 行,在 __call 中
返回 self.func(*args)
文件“frame.py”,第 34 行,在 compStats 中
stats.show(ch, userName)
文件 "C:\Users\Aa\AppData\Local\Programs\Python\Python35-32\stats.py", 第 17 行,显示中
li = soup.find_all('table', class_='table table-condensed')[0].find_all('td')
IndexError: 列表索引超出范围
我无法理解为什么代码无法在这里工作。请帮忙!
【问题讨论】:
标签: python tkinter beautifulsoup indexoutofrangeexception