F
F
Fox7772020-04-22 00:18:29
Python
Fox777, 2020-04-22 00:18:29

Why is the code not working?

import vk_api
import time
import random
import requests
from bs4 import BeautifulSoup

url = 'https://koronavirusa.site/ru'
page = requests.get(url)
soup = BeautifulSoup(page.text, "html.parser")
container = soup.find('div', class_='sppb-container-inner')
data = container.find_all('div', class_='sppb-animated-number')

infected = data[0].text
died = data[1].text
healed = data[2].text

url1 = 'https://www.coronavirussia.online/'
page1 = requests.get(url1)
soup1 = BeautifulSoup(page1.text, "html.parser")
stat1 = soup1.findAll('div', class_='h5 mb-0 font-weight-bold text-gray-800')
stat3 = soup1.findAll('div', class_='h5 mb-0 mr-3 font-weight-bold text-gray-800')
infected1 = stat1[2].text
died1 = stat1[3].text
healed1 = stat3[1].text

token = "61296b6fa92acd0d1f0f07f7f599164f6fb2652b28b9780a91166323d939bba891566d2a52b268bd24016"

vk = vk_api.VkApi(token=token)

vk._auth_token()

while True:
    try:
        messages = vk.method("messages.getConversations", {"offset": 0, "count": 20, "filter": "unanswered"})
        if messages["count"] >= 1:
            id = messages["items"][0]["last_message"]["from_id"]
            body = messages["items"][0]["last_message"]["text"]
            if body.lower() == "мир":
                vk.method("messages.send",
                          {"peer_id": id, "message": f'''Заражено: {infected}
Умерло: {died}
Выздоровело: {healed}''', "random_id": random.randint(1, 2147483647)})
            elif body.lower() == "россия":
                vk.method("messages.send",
                          {"peer_id": id, "message": f'''Заражено: {infected1}
Умерло: {died1}
Выздоровело: {healed1}''', "random_id": random.randint(1, 2147483647)})
            else:
                vk.method("messages.send",
                          {"peer_id": id, "message": "Не понял тебя!", "random_id": random.randint(1, 2147483647)})
    except Exception as E:
        time.sleep(1)


Ps Before that, everything worked fine! But the error is in

line 13, in
infected = data[0].text
IndexError: list index out of range

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Karbivnichy, 2020-04-22
@Fox7777

Why is the code not working?
- because cosmetic changes were made on the first site, blocks were added, etc.
A week ago, there was only one div on the site with the class 'sppb-container-inner', and today there are already 4. But the find method only finds the first tag on the page, regardless of the total number.
As a workaround, you can replace the find method with the select_one method :
# container = soup.find_all('div', class_='sppb-container-inner')
container = soup.select_one('div.sppb-row-container:nth-child(4) > div:nth-child(1)')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question