@night_7182

Ошибка str не могу исправить, как ее исправить?

Вылазит вот такая вот ошибка
Task exception was never retrieved
future: <Task finished name='Task-7' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\sa1nt\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py:407> exception=TypeError('can only concatenate str (not "NoneType") to str')>
Traceback (most recent call last):
  File "C:\Users\sa1nt\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "C:\Users\sa1nt\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates
    return await asyncio.gather(*tasks)
  File "C:\Users\sa1nt\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "C:\Users\sa1nt\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 256, in process_update
    return await self.message_handlers.notify(update.message)
  File "C:\Users\sa1nt\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "C:\Users\sa1nt\Desktop\parser.py", line 41, in parser
    caption="<b>" + name + "<b>\n<i>" + price + f"<i>\n<a href='{url}'> Ссылка на сайт</a>",
TypeError: can only concatenate str (not "NoneType") to str

Код такой
from urllib import request
import requests
from bs4 import BeautifulSoup
from aiogram import Bot, Dispatcher,executor,types


bot = Bot("")
dp = Dispatcher(bot) 

@dp.message_handler(commands=['start'])
async def start(message: types.message):
   await bot.send_message(message.chat.id, """
Привет, я бот который парсит сообщения в <b><a href="https://lalafo.kg"> lalafo</a></b>

Для того, что чтобы я отправил тебе объявления, введи в поле его названия...""",
parse_mode = 'html', disable_web_page_preview=1)
   
   
@dp.message_handler(content_types=['text'])
async def parser(message: types.message):
   url="https://lalafo.kg/kyrgyzstan/q-" + message.text
   request = requests.get(url)
   soup = BeautifulSoup(request.text, "html.parser")
   
   all_link = soup.find_all("a", class_="adTile-title")
   for link in all_link:
      url = "https://lalafo.kg/" + link["href"]
      request = requests.get(url)
      soup = BeautifulSoup(request.text, "html.parser")
      
      name = soup.find("h1", class_="Heading secondary-small")
       
      price = soup.find("a", class_="heading")
      
      tel = soup.find("a", class_='linkButton medium secondary')
      
      img = soup.find("div", class_="carousel__img-wrap")

      
      await bot.send_photo(message.chat.id, img,
      caption="<b>" + name + "<b>\n<i>" + price + f"<i>\n<a href='{url}'> Ссылка на сайт</a>",
      parse_mode='html')
      
      
executor.start_polling(dp)

Помогите пожалуйста исправить
  • Вопрос задан
  • 191 просмотр
Пригласить эксперта
Ответы на вопрос 2
phaggi
@phaggi Куратор тега Python
лужу, паяю, ЭВМы починяю
Какая-то из переменных price, name, url приходит из парсера со значением None. Чтобы ошибки не было, надо предварительно проверять каждую переменную на None, либо перехватывать ошибку и обрабатывать (так прямее).
Ответ написан
Комментировать
lxsmkv
@lxsmkv
Test automation engineer
Правильно конечно отлавливать значения, но для быстрого дебаггинга можно сделать и так
caption="<b>" + str(name) + "<b>\n<i>" + str(price) + f"<i>\n<a href='{url}'> Ссылка на сайт</a>",

Т.е. просто при конкатенации ковертировать значения в строковые, и тогда если переменная получит значение None, то оно в строке будет прописано как None. Будет сразу видно откуда пустое значение приходит.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы