Python 美化组列表索引超出范围错误,包含多个.contents

Python 美化组列表索引超出范围错误,包含多个.contents,python,beautifulsoup,Python,Beautifulsoup,所以我用beautifulsoup在yahoo finance上刮取一些股票价格。我目前得到的日期和收盘价分别 我得到一个索引器:列表索引超出范围,代码close=td.contents[5]。text但[5]未超出范围。如果我要删除所有close,我只能在代码中只有一个.contents的情况下导出日期数据框。我怎样才能解决这个问题?我的代码如下 从请求导入获取 从bs4导入BeautifulSoup 作为pd进口熊猫 导入csv 日期列表=[] 关闭列表=[] url='1〕https://

所以我用beautifulsoup在yahoo finance上刮取一些股票价格。我目前得到的日期和收盘价分别

我得到一个索引器:列表索引超出范围,代码
close=td.contents[5]。text
但[5]未超出范围。如果我要删除所有close,我只能在代码中只有一个.contents的情况下导出日期数据框。我怎样才能解决这个问题?我的代码如下

从请求导入获取
从bs4导入BeautifulSoup
作为pd进口熊猫
导入csv
日期列表=[]
关闭列表=[]
url='1〕https://finance.yahoo.com/quote/TSLA/history?period1=512784000&period2=1588982400&interval=1d&filter=history&frequency=1d'
response=get(url)
soup=BeautifulSoup(response.text'html.parser')
chode=soup.find('table',{'class':'W(100%)M(0)})
对于chode中的tr:
tr.find('tr')
对于tr中的td:
日期=td.contents[0]。文本
日期列表。附加(日期)
日期df=pd.DataFrame(日期列表)
close=td.contents[5]。文本
关闭列表。追加(关闭)
close_df=pd.DataFrame(close_列表)
df=pd.concat([date\u df,close\u df],axis=1)
df.to_csv(“TSLA.csv”)
错误
---------------------------------------------------------------------------
索引器回溯(最后一次最近调用)
在里面
16日期df=pd.DataFrame(日期列表)
17
--->18 close=td.contents[5]。文本
19关闭列表。追加(关闭)
20
索引器:列表索引超出范围

如果您在for循环中添加检查
len(td.contents)<6
并打印出相应的
td.contents
,您将看到实际上有一个
td.contents
值的列表索引超出范围。打印出来的结果如下所示:

for tr in chode:
    tr.find('tr')
    for td in tr:
        if len(td.contents) >= 6: # check that the td has enough elements
            date = td.contents[0].text
            date_list.append(date) # build the list
            close = td.contents[5].text
            close_list.append(close) # build the list

    date_df = pd.DataFrame(date_list) # create a df after the entire list is built
    close_df = pd.DataFrame(close_list) # create a df after the entire list is built

    df = pd.concat( [date_df, close_df], axis=1)
    df.to_csv("TSLA.csv")
[*调整分割的收盘价。**调整股息和分割的收盘价。]

此外,由于您的代码没有在td中的
for tr下面正确缩进,因此很难判断您打算成为for循环的一部分的行。我猜你想做的事情更像这样:

for tr in chode:
    tr.find('tr')
    for td in tr:
        if len(td.contents) >= 6: # check that the td has enough elements
            date = td.contents[0].text
            date_list.append(date) # build the list
            close = td.contents[5].text
            close_list.append(close) # build the list

    date_df = pd.DataFrame(date_list) # create a df after the entire list is built
    close_df = pd.DataFrame(close_list) # create a df after the entire list is built

    df = pd.concat( [date_df, close_df], axis=1)
    df.to_csv("TSLA.csv")