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)
I have to crawl, so I'm trying to hard-coding by searching the Internet, but I keep getting a list index out of range error on Python. I'm not sure what to do. Please. I'm in a bit of a hurry😢😢😢
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
This means that the index of the list exceeds the possible index range of the list.
So, in the case of this error, you can look at the code that indexes the list variables and look through it.
Among the codes where the error occurs, posts[0].text
also has posts[0]
. I'm trying to access the first element of the list, but can this cause an error?
There is. An error occurs if the list is an empty list (length is 0).
© 2025 OneMinuteCode. All rights reserved.