why did i got IndexError: list index out of range message?











up vote
-3
down vote

favorite












import urllib # cmd- pip install requests
import bs4 # 실행전cmd- pip install BeautifulSoup4 설치
import matplotlib.pyplot # 만들어진 데이터 포인트를 graph로 출력, 사용하기전 cmd-pip install matplotlib 실행
from datetime import datetime
company=input('찾으시고 싶은 회사명을 Ticker는 stock symbol로 적어주세요(ex)apple=appl) :' )

def get_company_data(company):
findothercompany=company # https://www.nasdaq.com/symbol/aapl/dividend-history 창에서 appl부분을 인풋값으로 변환
data= # 공백 리스트 형식으로 append 함수를 이용해 추가할 예정
dividendplot= # 공백 리스트에 데이터값을 받아와서 plot함수를 이용해 graph를 그린다.
url='https://www.nasdaq.com/symbol/'+findothercompany+'/dividend-history' # nasdaq사이트에서 dividend history를 찾는것 없을수도 있다.
print('본 데이터는 NASDAQ의 '+url+'를 참고한 것입니다.')
tables=bs4.BeautifulSoup(urllib.request.urlopen(url).read(),features='lxml').find_all('table')# lxml은 코드들을 html 형식으로 가져오는것 (1조 발표 html형식)
#print(len(tables))
dividend_data=tables[2].find_all('tr')
#print(dividend_data[0])
#print(dividend_data[1])
for tr in dividend_data[1:]:
tds=tr.find_all('td')
exdate=tds[0].text
Type=tds[1].text
CashAmount=tds[2].text
Declarationdate=tds[3].text
Recorddate=tds[4].text
Paymentdate=tds[5].text
data.append([exdate,Type,CashAmount,Declarationdate,Recorddate,Paymentdate])
dividendplot.append([Paymentdate,float(CashAmount)])

return data,dividendplot


dividenddata,dividendplot=get_company_data(company)
print(dividenddata)


then I got this message:



Traceback (most recent call last):
File "C:/Users/월토커/Desktop/금융소프트웨어 project.py", line 32, in <module>
dividenddata,dividendplot=get_company_data(company)
File "C:/Users/월토커/Desktop/금융소프트웨어 project.py", line 22, in get_company_data
Declarationdate=tds[3].text
IndexError: list index out of range









share|improve this question
























  • I think you should start debugging your code by printing the content of the tds array and see what's it like. Most probably it will have less than 3 elements....
    – toti08
    Nov 12 at 10:52












  • Obviously there a tr that has 3 tds.
    – Klaus D.
    Nov 12 at 11:06










  • the problem is when i type appl. but when i type dal it works
    – 창조박
    Nov 12 at 11:08

















up vote
-3
down vote

favorite












import urllib # cmd- pip install requests
import bs4 # 실행전cmd- pip install BeautifulSoup4 설치
import matplotlib.pyplot # 만들어진 데이터 포인트를 graph로 출력, 사용하기전 cmd-pip install matplotlib 실행
from datetime import datetime
company=input('찾으시고 싶은 회사명을 Ticker는 stock symbol로 적어주세요(ex)apple=appl) :' )

def get_company_data(company):
findothercompany=company # https://www.nasdaq.com/symbol/aapl/dividend-history 창에서 appl부분을 인풋값으로 변환
data= # 공백 리스트 형식으로 append 함수를 이용해 추가할 예정
dividendplot= # 공백 리스트에 데이터값을 받아와서 plot함수를 이용해 graph를 그린다.
url='https://www.nasdaq.com/symbol/'+findothercompany+'/dividend-history' # nasdaq사이트에서 dividend history를 찾는것 없을수도 있다.
print('본 데이터는 NASDAQ의 '+url+'를 참고한 것입니다.')
tables=bs4.BeautifulSoup(urllib.request.urlopen(url).read(),features='lxml').find_all('table')# lxml은 코드들을 html 형식으로 가져오는것 (1조 발표 html형식)
#print(len(tables))
dividend_data=tables[2].find_all('tr')
#print(dividend_data[0])
#print(dividend_data[1])
for tr in dividend_data[1:]:
tds=tr.find_all('td')
exdate=tds[0].text
Type=tds[1].text
CashAmount=tds[2].text
Declarationdate=tds[3].text
Recorddate=tds[4].text
Paymentdate=tds[5].text
data.append([exdate,Type,CashAmount,Declarationdate,Recorddate,Paymentdate])
dividendplot.append([Paymentdate,float(CashAmount)])

return data,dividendplot


dividenddata,dividendplot=get_company_data(company)
print(dividenddata)


then I got this message:



Traceback (most recent call last):
File "C:/Users/월토커/Desktop/금융소프트웨어 project.py", line 32, in <module>
dividenddata,dividendplot=get_company_data(company)
File "C:/Users/월토커/Desktop/금융소프트웨어 project.py", line 22, in get_company_data
Declarationdate=tds[3].text
IndexError: list index out of range









share|improve this question
























  • I think you should start debugging your code by printing the content of the tds array and see what's it like. Most probably it will have less than 3 elements....
    – toti08
    Nov 12 at 10:52












  • Obviously there a tr that has 3 tds.
    – Klaus D.
    Nov 12 at 11:06










  • the problem is when i type appl. but when i type dal it works
    – 창조박
    Nov 12 at 11:08















up vote
-3
down vote

favorite









up vote
-3
down vote

favorite











import urllib # cmd- pip install requests
import bs4 # 실행전cmd- pip install BeautifulSoup4 설치
import matplotlib.pyplot # 만들어진 데이터 포인트를 graph로 출력, 사용하기전 cmd-pip install matplotlib 실행
from datetime import datetime
company=input('찾으시고 싶은 회사명을 Ticker는 stock symbol로 적어주세요(ex)apple=appl) :' )

def get_company_data(company):
findothercompany=company # https://www.nasdaq.com/symbol/aapl/dividend-history 창에서 appl부분을 인풋값으로 변환
data= # 공백 리스트 형식으로 append 함수를 이용해 추가할 예정
dividendplot= # 공백 리스트에 데이터값을 받아와서 plot함수를 이용해 graph를 그린다.
url='https://www.nasdaq.com/symbol/'+findothercompany+'/dividend-history' # nasdaq사이트에서 dividend history를 찾는것 없을수도 있다.
print('본 데이터는 NASDAQ의 '+url+'를 참고한 것입니다.')
tables=bs4.BeautifulSoup(urllib.request.urlopen(url).read(),features='lxml').find_all('table')# lxml은 코드들을 html 형식으로 가져오는것 (1조 발표 html형식)
#print(len(tables))
dividend_data=tables[2].find_all('tr')
#print(dividend_data[0])
#print(dividend_data[1])
for tr in dividend_data[1:]:
tds=tr.find_all('td')
exdate=tds[0].text
Type=tds[1].text
CashAmount=tds[2].text
Declarationdate=tds[3].text
Recorddate=tds[4].text
Paymentdate=tds[5].text
data.append([exdate,Type,CashAmount,Declarationdate,Recorddate,Paymentdate])
dividendplot.append([Paymentdate,float(CashAmount)])

return data,dividendplot


dividenddata,dividendplot=get_company_data(company)
print(dividenddata)


then I got this message:



Traceback (most recent call last):
File "C:/Users/월토커/Desktop/금융소프트웨어 project.py", line 32, in <module>
dividenddata,dividendplot=get_company_data(company)
File "C:/Users/월토커/Desktop/금융소프트웨어 project.py", line 22, in get_company_data
Declarationdate=tds[3].text
IndexError: list index out of range









share|improve this question















import urllib # cmd- pip install requests
import bs4 # 실행전cmd- pip install BeautifulSoup4 설치
import matplotlib.pyplot # 만들어진 데이터 포인트를 graph로 출력, 사용하기전 cmd-pip install matplotlib 실행
from datetime import datetime
company=input('찾으시고 싶은 회사명을 Ticker는 stock symbol로 적어주세요(ex)apple=appl) :' )

def get_company_data(company):
findothercompany=company # https://www.nasdaq.com/symbol/aapl/dividend-history 창에서 appl부분을 인풋값으로 변환
data= # 공백 리스트 형식으로 append 함수를 이용해 추가할 예정
dividendplot= # 공백 리스트에 데이터값을 받아와서 plot함수를 이용해 graph를 그린다.
url='https://www.nasdaq.com/symbol/'+findothercompany+'/dividend-history' # nasdaq사이트에서 dividend history를 찾는것 없을수도 있다.
print('본 데이터는 NASDAQ의 '+url+'를 참고한 것입니다.')
tables=bs4.BeautifulSoup(urllib.request.urlopen(url).read(),features='lxml').find_all('table')# lxml은 코드들을 html 형식으로 가져오는것 (1조 발표 html형식)
#print(len(tables))
dividend_data=tables[2].find_all('tr')
#print(dividend_data[0])
#print(dividend_data[1])
for tr in dividend_data[1:]:
tds=tr.find_all('td')
exdate=tds[0].text
Type=tds[1].text
CashAmount=tds[2].text
Declarationdate=tds[3].text
Recorddate=tds[4].text
Paymentdate=tds[5].text
data.append([exdate,Type,CashAmount,Declarationdate,Recorddate,Paymentdate])
dividendplot.append([Paymentdate,float(CashAmount)])

return data,dividendplot


dividenddata,dividendplot=get_company_data(company)
print(dividenddata)


then I got this message:



Traceback (most recent call last):
File "C:/Users/월토커/Desktop/금융소프트웨어 project.py", line 32, in <module>
dividenddata,dividendplot=get_company_data(company)
File "C:/Users/월토커/Desktop/금융소프트웨어 project.py", line 22, in get_company_data
Declarationdate=tds[3].text
IndexError: list index out of range






python beautifulsoup web-crawler






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 at 10:52









toti08

1,74721523




1,74721523










asked Nov 12 at 10:39









창조박

31




31












  • I think you should start debugging your code by printing the content of the tds array and see what's it like. Most probably it will have less than 3 elements....
    – toti08
    Nov 12 at 10:52












  • Obviously there a tr that has 3 tds.
    – Klaus D.
    Nov 12 at 11:06










  • the problem is when i type appl. but when i type dal it works
    – 창조박
    Nov 12 at 11:08




















  • I think you should start debugging your code by printing the content of the tds array and see what's it like. Most probably it will have less than 3 elements....
    – toti08
    Nov 12 at 10:52












  • Obviously there a tr that has 3 tds.
    – Klaus D.
    Nov 12 at 11:06










  • the problem is when i type appl. but when i type dal it works
    – 창조박
    Nov 12 at 11:08


















I think you should start debugging your code by printing the content of the tds array and see what's it like. Most probably it will have less than 3 elements....
– toti08
Nov 12 at 10:52






I think you should start debugging your code by printing the content of the tds array and see what's it like. Most probably it will have less than 3 elements....
– toti08
Nov 12 at 10:52














Obviously there a tr that has 3 tds.
– Klaus D.
Nov 12 at 11:06




Obviously there a tr that has 3 tds.
– Klaus D.
Nov 12 at 11:06












the problem is when i type appl. but when i type dal it works
– 창조박
Nov 12 at 11:08






the problem is when i type appl. but when i type dal it works
– 창조박
Nov 12 at 11:08














1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










your code is fine but appl has no data, check https://www.nasdaq.com/symbol/appl/dividend-history try with another like ppl



check your td length if it length lower than 6 skip the loop



tds=tr.find_all('td')
if len(tds) < 6:
continue # or break





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53260420%2fwhy-did-i-got-indexerror-list-index-out-of-range-message%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    your code is fine but appl has no data, check https://www.nasdaq.com/symbol/appl/dividend-history try with another like ppl



    check your td length if it length lower than 6 skip the loop



    tds=tr.find_all('td')
    if len(tds) < 6:
    continue # or break





    share|improve this answer

























      up vote
      0
      down vote



      accepted










      your code is fine but appl has no data, check https://www.nasdaq.com/symbol/appl/dividend-history try with another like ppl



      check your td length if it length lower than 6 skip the loop



      tds=tr.find_all('td')
      if len(tds) < 6:
      continue # or break





      share|improve this answer























        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        your code is fine but appl has no data, check https://www.nasdaq.com/symbol/appl/dividend-history try with another like ppl



        check your td length if it length lower than 6 skip the loop



        tds=tr.find_all('td')
        if len(tds) < 6:
        continue # or break





        share|improve this answer












        your code is fine but appl has no data, check https://www.nasdaq.com/symbol/appl/dividend-history try with another like ppl



        check your td length if it length lower than 6 skip the loop



        tds=tr.find_all('td')
        if len(tds) < 6:
        continue # or break






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 at 12:15









        ewwink

        9,34922236




        9,34922236






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53260420%2fwhy-did-i-got-indexerror-list-index-out-of-range-message%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            List item for chat from Array inside array React Native

            Thiostrepton

            Caerphilly