A
A
Athensky2020-04-27 10:32:51
Python
Athensky, 2020-04-27 10:32:51

IndexError: list index out of range discord.py?

Hi, I just recently started making a bot for a Discord server.
And now I ran into such a problem, writes:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
The code itself:

spoiler
import requests
from lxml import html
from bs4 import BeautifulSoup
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from fake_useragent import UserAgent
from datetime import datetime

ua = UserAgent()
headers = {'User-Agent': ua.chrome}

Bot = commands.Bot(command_prefix='*')

@Bot.event
async def on_ready():
    print("Бот активен...")
    await Bot.change_presence(activity=discord.Game(name='*help'))

@Bot.command(pass_context=True)
async def погода(ctx, arg):
    url = f"https://www.google.com/search?q=Погода+{arg}"
    
    pagecontent = requests.get(url, headers=headers)
    
    tree = html.fromstring(pagecontent.content)

    icon_url = ctx.guild.icon_url

    maxtemp = tree.xpath("/html/body[@id='gsr']/div[@id='main']/div[@id='cnt']/div[@class='mw'][2]/div[@id='rcnt']/div[@class='col']/div[@id='center_col']/div[@id='res']/div[@id='search']/div/div[@id='rso']/div[@class='g knavi obcontainer mod']/div/div[@id='wob_wc']/div[@class='gic']/div[@id='wob_dp']/div[@class='wob_df wob_ds']/div[3]/div[@class='vk_gy']/span[@class='wob_t'][1]")[0].text_content() #Думаю что ошибка здесь
    mintemp = tree.xpath("/html/body[@id='gsr']/div[@id='main']/div[@id='cnt']/div[@class='mw'][2]/div[@id='rcnt']/div[@class='col']/div[@id='center_col']/div[@id='res']/div[@id='search']/div/div[@id='rso']/div[@class='g knavi obcontainer mod']/div/div[@id='wob_wc']/div[@class='gic']/div[@id='wob_dp']/div[@class='wob_df wob_ds']/div[3]/div[@class='vk_lgy']/span[@class='wob_t'][1]")[0].text_content() #Здесь
    currenttemp = tree.xpath("/html/body[@id='gsr']/div[@id='main']/div[@id='cnt']/div[@class='mw'][2]/div[@id='rcnt']/div[@class='col']/div[@id='center_col']/div[@id='res']/div[@id='search']/div/div[@id='rso']/div[@class='g knavi obcontainer mod']/div/div[@id='wob_wc']/div[@id='wob_d']/div/div[1]/div/div[@class='vk_bk sol-tmp']/span[@id='wob_tm']")[0].text_content() #Здесь
    
    waterp = tree.xpath("/html/body[@id='gsr']/div[@id='main']/div[@id='cnt']/div[@class='mw'][2]/div[@id='rcnt']/div[@class='col']/div[@id='center_col']/div[@id='res']/div[@id='search']/div/div[@id='rso']/div[@class='g knavi obcontainer mod']/div/div[@id='wob_wc']/div[@id='wob_d']/div/div[@class='vk_gy vk_sh wob-dtl']/div[2]/span[@id='wob_hm']")[0].text_content() #Здесь
    veter = tree.xpath("/html/body[@id='gsr']/div[@id='main']/div[@id='cnt']/div[@class='mw'][2]/div[@id='rcnt']/div[@class='col']/div[@id='center_col']/div[@id='res']/div[@id='search']/div/div[@id='rso']/div[@class='g knavi obcontainer mod']/div/div[@id='wob_wc']/div[@id='wob_d']/div/div[@class='vk_gy vk_sh wob-dtl']/div[3]/span/span[@id='wob_ws']")[0].text_content() #
    pogoda = tree.xpath("/html/body[@id='gsr']/div[@id='main']/div[@id='cnt']/div[@class='mw'][2]/div[@id='rcnt']/div[@class='col']/div[@id='center_col']/div[@id='res']/div[@id='search']/div/div[@id='rso']/div[@class='g knavi obcontainer mod']/div/div[@id='wob_wc']/span/div[@id='wob_dcp']/span[@id='wob_dc']")[0].text_content() #Здесь

    embed = discord.Embed(title = f'Прогноз погоды для города {arg}', color=0x3e3e3e)
    embed.set_footer(text=f'{datetime.date(datetime.now())}')
    embed.description = f""":thermometer:Температура сейчас: **{currenttemp}°С**

:chart_with_upwards_trend:Макс.температура: **{maxtemp}°С**

:chart_with_downwards_trend:Мин.температура: **{mintemp}°С**

:white_sun_behind_cloud_with_rain:Погода: **{pogoda}**

:dash:Ветер: **{veter}**

:droplet:Влажность: **{waterp}**
"""
    embed.set_thumbnail(url=icon_url)
    await ctx.send(embed=embed)

Bot.run("Мой токен")

Help, I will be glad to any answer.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Karbivnichy, 2020-04-27
@Athensky

/html/body[@id='gsr']/div[@id='main']...
- What are you smoking there?
There is a special library for the weather - pyowm
If you want to parse google, then divide the code into functions. Make a separate function for parsing, and return data from it. It's easier to debug a function than the entire code of a project.
Here's an example (I'm not sure it's correct, but it works):
def getWeather(city_):
  response = requests.get(f'https://www.google.com/search?q=Погода {city_}',headers=headers)
  soup = BeautifulSoup(response.text,"html.parser")
  city = soup.select_one('#wob_loc').text.split(',')[0] # город
  current_temp = soup.select_one('#wob_tm').text # температурв
  cloudiness = soup.select_one('#wob_dc').text #"облачность"
  chanceOfPrecipitation = soup.select_one('#wob_pp').text # вероятность осадков
  humidity = soup.select_one('#wob_hm').text # влажность
  wind = soup.select_one('#wob_ws').text # ветер

  weather = {	'city':city,
        'current_temp':current_temp,
        'cloudiness':cloudiness,
        'chanceOfPrecipitation':chanceOfPrecipitation,
        'humidity':humidity,
        'wind':wind
        }
  return weather

Next, the function call:
weather = getWeather('киев')

print(f'''
Город: {weather['city']}
Температура: {weather['current_temp']}
Облачность: {weather['cloudiness']}
Вероятность осадков: {weather['chanceOfPrecipitation']}
Влажность: {weather['humidity']}
Ветер: {weather['wind']}
  ''')

Console output:
Город: Київ
Температура: 12
Облачность: Мінлива хмарність
Вероятность осадков: 0%
Влажность: 39%
Ветер: 24 км/год

PS: There are no checks in the code!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question