我得到一个超出范围错误的下标,我似乎无法通过某些原因通过,任何帮助将不胜感激?
我已经更改了变量以使其工作但仍然无法解决。由于某种原因,线程参数似乎没有考虑到我的两个变量
由于
from threading import Thread
import urllib.request
import re
def th(ur):
base = "http://finance.yahoo.com/q?s="+ur
regex = '<span id="yfs_184_'+ur.lower()+'">(.+?)</span>'
pattern = re.compile(regex)
htmltext = urllib.request.urlopen(base).read().decode('utf-8')
results = re.findall(pattern,htmltext)
print ("the price of "+str(ur)+" is "+str(results[0]))
symbolslist = ["aapl","goog"]
print (symbolslist)
threadlist = []
for u in symbolslist:
t = Thread(target = th, args= (u,))
t.start()
threadlist.append(t)
for b in threadlist:
b.join()
完整追溯:
C:\Python34\python.exe C:/Users/User/PycharmProjects/untitled/Hellopython.py
['aapl', 'goog']
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python34\lib\threading.py", line 921, in _bootstrap_inner
self.run()
File "C:\Python34\lib\threading.py", line 869, in run
self._target(*self._args, **self._kwargs)
File "C:/Users/User/PycharmProjects/untitled/Hellopython.py", line 12, in th
print ("the price of "+str(ur)+" is "+str(results[0]))
IndexError: list index out of range
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Python34\lib\threading.py", line 921, in _bootstrap_inner
self.run()
File "C:\Python34\lib\threading.py", line 869, in run
self._target(*self._args, **self._kwargs)
File "C:/Users/User/PycharmProjects/untitled/Hellopython.py", line 12, in th
print ("the price of "+str(ur)+" is "+str(results[0]))
IndexError: list index out of range
Process finished with exit code 0
答案 0 :(得分:0)
您的问题与多线程无关,只是因为results
是一个空列表。正如评论所说,在打印前检查它的长度。
def th(ur):
base = "http://finance.yahoo.com/q?s="+ur
regex = '<span id="yfs_184_'+ur.lower()+'">(.+?)</span>'
pattern = re.compile(regex)
htmltext = urllib.request.urlopen(base).read().decode('utf-8')
results = re.findall(pattern,htmltext)
if len(results) > 0:
print("the price of "+str(ur)+" is "+str(results[0]))
else:
print("results is empty")