Telegram - бот на сервере выдаёт ошибку. Хотелось бы узнать почему?

Telegram - бот на сервере выдаёт ошибку. Код написан на Python. Налокальном компьютере работает без сбоев. Не пойму в чём причина. Библиотеки все установлены. Сервер: https://www.pythonanywhere.com/ Если кто знает подскажите в чём причина. Это код бота:

import requests  # pip install requests
# from PIL import Image
from telebot import *
from bs4 import BeautifulSoup  # pip install bs4

TOKEN = ''
bot = telebot.TeleBot(TOKEN)


@bot.message_handler(commands=['start'])
def command(message):
    bot.reply_to(message, 'Введите название блюда...')
    bot.register_callback_query_handler(message, bodyes)


@bot.message_handler(content_types=['text'])
def bodyes(mess):
    name = mess.text.lower()

    url = f'https://povar.ru/xmlsearch?query={name}&page=1'
    data = requests.get(url).text
    block = BeautifulSoup(data, 'lxml')
    heads = block.find_all('div', class_='recipe')
    # print(len(heads))
    for i in heads:
        w = i.find_next('a').get('href')
        # print('https://povar.ru'+w)
        get_url = ('https://povar.ru' + w)
        sock = requests.get(get_url).text
        dock = BeautifulSoup(sock, 'lxml')
        head = dock.find('h1', class_='detailed fn')
        photo = dock.find('div', class_='bigImgBox').find('a').get('href')
        try:
            bot.send_photo(mess.chat.id, photo)
        except:
            bot.send_message(mess.chat.id, 'No photo')
        try:
            bot.send_message(mess.chat.id, head.text.strip())
        except:
            bot.send_message(mess.chat.id, 'No head')
        opiss = dock.find('span', class_='detailed_full description')
        bot.send_message(mess.chat.id, opiss.text.strip())
        sostav = dock.find('div', class_='ingredients_wrapper').find('h2')
        bot.send_message(mess.chat.id, sostav.text.strip(), parse_mode='Markdown')
        lists = dock.find('div', class_='ingredients_wrapper').find('ul').find_all('li')
        for el in lists:
            try:
                bot.send_message(mess.chat.id, ' '.join(el.text.strip().split()))
            except:
                continue
        # print(' '.join(lists[0].text.strip().split()))
        podhead = dock.find('h2', class_='span')
        try:
            bot.send_message(mess.chat.id, podhead.text.strip())
        except:
            continue
        try:
            instructiuns = dock.find('div', class_='instructions').find_all('div',
                                                                            class_='detailed_step_description_big')
            for det in instructiuns:
                try:
                    bot.send_message(mess.chat.id, ' '.join(det.text.strip().split()))
                    # print(det.text.strip())
                except:
                    continue
        except:
            # instructiuns = dock.find('span', itemprop='recipeInstructions')
            bot.send_message(mess.chat.id, "Данные отсутствуют")


bot.polling(none_stop=True)

это ошибка которую выдаёт сервер:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", line 696, in urlopen
    self._prepare_proxy(conn)
  File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", line 964, in _prepare_proxy
    conn.connect()
  File "/usr/local/lib/python3.9/site-packages/urllib3/connection.py", line 366, in connect
    self._tunnel()
  File "/usr/local/lib/python3.9/http/client.py", line 903, in _tunnel
    raise OSError(f"Tunnel connection failed: {code} {message.strip()}")
OSError: Tunnel connection failed: 403 Forbidden
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/requests/adapters.py", line 439, in send
    resp = conn.urlopen(
  File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", line 755, in urlopen
    retries = retries.increment(
  File "/usr/local/lib/python3.9/site-packages/urllib3/util/retry.py", line 573, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='povar.ru', port=443): Max retries exceeded with url: /xmlsearch?query=%D0%BA%D1%83%D1%80%D0%B8%D1%86%D0%B0&page=1 (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/kilion74/mysite/recepty_bot_2.py", line 71, in <module>
    bot.polling(none_stop=True)
  File "/home/kilion74/.local/lib/python3.9/site-packages/telebot/__init__.py", line 1178, in polling
    self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
  File "/home/kilion74/.local/lib/python3.9/site-packages/telebot/__init__.py", line 1253, in __threaded_polling
    raise e
  File "/home/kilion74/.local/lib/python3.9/site-packages/telebot/__init__.py", line 1215, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "/home/kilion74/.local/lib/python3.9/site-packages/telebot/util.py", line 150, in raise_exceptions
    raise self.exception_info
  File "/home/kilion74/.local/lib/python3.9/site-packages/telebot/util.py", line 93, in run
    task(*args, **kwargs)
  File "/home/kilion74/.local/lib/python3.9/site-packages/telebot/__init__.py", line 8449, in _run_middlewares_and_handler
    result = handler['function'](message)
  File "/home/kilion74/mysite/recepty_bot_2.py", line 21, in bodyes
    data = requests.get(url).text
  File "/usr/local/lib/python3.9/site-packages/requests/api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/requests/sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.9/site-packages/requests/sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/requests/adapters.py", line 510, in send
    raise ProxyError(e, request=request)
requests.exceptions.ProxyError: HTTPSConnectionPool(host='povar.ru', port=443): Max retries exceeded with url: /xmlsearch?query=%D0%BA%D1%83%D1%80%D0%B8%D1%86%D0%B0&p
age=1 (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden')))

Ответы (1 шт):

Автор решения: Daniel

Прошу обратить ваше внимание на следующую строчку в логе ошибки:

OSError: Tunnel connection failed: 403 Forbidden

Учитывая что ошибка появляется когда бот запускается на сервере, могу предположить что проблема связана с настройками на стороне сервера, которые блокируют запросы от неизвестных агентов (Об этом громко говорит ошибка 403, которая дословно значит что "Доступ запрещён")

Решение:

Попробуйте изменить эту строчку кода:

data = requests.get(url).text

На следующую:

headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
}

data = requests.get(url, headers=headers).text

Это поможет замаскироваться под браузер Chrome, что бы избежать блокировки скрейпинга сервером

→ Ссылка