파이썬 list index out of range 에러

조회수 2446회
import requests
from bs4 import BeautifulSoup
import os
import time

import telegram

bot = telegram.Bot(token='123535:AASAAASDFDFDSFSD')
chat_id = bot.getUpdates()[-1].message.chat.id


BASE_DIR = os.path.dirname(os.path.abspath(__file__))

while True:
    req = requests.get('WebURL')
    req.encoding = 'euc-kr'


    soup = BeautifulSoup(req.content.decode('euc-kr','replace'))
    posts = soup.select('Select')
    latest = posts[0].text



    with open(os.path.join(BASE_DIR, 'a.txt'), 'r+') as f_read:
        before = f_read.readline()
        if before != latest:
            bot.sendMessage(chat_id=chat_id, text='TEXT')


    with open(os.path.join(BASE_DIR, 'a.txt'), 'w+') as f_write:
        f_write.write(latest)
        f_write.close()

    time.sleep(5) 

급하게 크롤링 해야할 일이 생겨서 인터넷 검색으로 하드 코딩을 하는데 자꾸 파이썬에서 list index out of range 에러가 나옵니다. 어떻게 해야 할지 잘 모르겠습니다. 부탁드려요 조금 급합니다😢😢😢

soup = BeautifulSoup(req.content.decode('euc-kr','replace'))
Traceback (most recent call last):
File "/root/a.py", line 23, in <module>
latest = posts[0].text
IndexError: list index out of range

1 답변

  • list 의 index 가 list 의 가능한 인덱스 범위를 넘어선다는 말입니다.

    그래서, 이런 에러의 경우에는 리스트형 변수에 대해 인덱싱하는 형태의 코드를 찾아서 뚫어지게 보면 됩니다.

    에러가 발생하는 곳의 코드 중에 리스트 인덱싱하는 것은 posts[0].text 에서도 posts[0] 가 있습니다. 리스트의 첫번째 원소를 접근하려는 건데, 이게 에러가 발생할 수 있을까요?

    있습니다. 리스트가 빈 리스트(길이가 0)라면 에러가 발생합니다.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)