我在python中有一个列表
x = ['a','b','c']
Run Code Online (Sandbox Code Playgroud)
有3个元素.我想检查第4个元素是否存在而没有收到错误消息.
我该怎么办?
我创建了一个程序,该程序采用股票代码,抓取网络以查找每个股票代码的历史价格的CSV,并使用matplotlib绘制它们.几乎所有东西都运行正常,但我遇到了解析CSV以分离每个价格的问题.
我得到的错误是:
price = [float(row [4])for csv_rows中的行]
IndexError:列表索引超出范围
我明白了问题所在,我只是不确定应该如何修复它.
(问题在于parseCSV()方法)
# Loop to chart multiple stocks
def chartStocks(*tickers):
for ticker in tickers:
chartStock(ticker)
# Single chart stock method
def chartStock(ticker):
url = "http://finance.yahoo.com/q/hp?s=" + str(ticker) + "+Historical+Prices"
sourceCode = requests.get(url)
plainText = sourceCode.text
soup = BeautifulSoup(plainText, "html.parser")
csv = findCSV(soup)
parseCSV(csv)
# Find the CSV URL
def findCSV(soupPage):
CSV_URL_PREFIX = 'http://real-chart.finance.yahoo.com/table.csv?s='
links = soupPage.findAll('a')
for link in links:
href = link.get('href', '')
if href.startswith(CSV_URL_PREFIX):
return href
# Parse …Run Code Online (Sandbox Code Playgroud)