После второй попытки запустить скрипт выдает "Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение"
После запуска телеграм бота , первый раз бот отрабатывает нормально , но при попытке запустить повторно не выключая его, приводит ошибку ,
upd я запускаю бота который принимает от пользователя url после чего запускается парсер (request) после первого парсера запускается второй парсер на selenium далее результат передается в телеграм бота,этот результат отправляет пользователю, ошибка заключается в то что при повторной попытки запустить парсер выдает ошибку
КОД ОШИБКИ
Task exception was never retrieved
future: <Task finished name='Task-36' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py:407> exception=MaxRetryError("HTTPConnectionPool(host='localhost', port=54060): Max retries exceeded with url: /session/9d671bafe2c7f836ad65a632287981ab/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001DD1D339580>: Failed to establish a new connection: [WinError 10061] Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение'))")>
Traceback (most recent call last):
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connection.py", line 174, in _new_conn
conn = connection.create_connection(
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\connection.py", line 95, in create_connection
raise err
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\connection.py", line 85, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen
httplib_response = self._make_request(
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 398, in _make_request
conn.request(method, url, **httplib_request_kw)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connection.py", line 239, in request
super(HTTPConnection, self).request(method, url, body=body, headers=headers)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1253, in request
self._send_request(method, url, body, headers, encode_chunked)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1299, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1248, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1008, in _send_output
self.send(msg)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 948, in send
self.connect()
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connection.py", line 205, in connect
conn = self._new_conn()
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connection.py", line 186, in _new_conn
raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x000001DD1D339580>: Failed to establish a new connection: [WinError 10061] Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\boxer\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\boxer\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\boxer\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\boxer\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\boxer\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\boxer\Desktop\test\telegram_steam_parser.py", line 52, in cheking_steam
helper_telega.starting()
File "c:\Users\boxer\Desktop\test\helper_telega.py", line 4, in starting
first_phasa()
File "c:\Users\boxer\Desktop\test\steam_checer.py", line 80, in first_phasa
starting2()
File "c:\Users\boxer\Desktop\test\helper_telega.py", line 9, in starting2
second_phasa()
File "c:\Users\boxer\Desktop\test\csgo_stats.py", line 37, in second_phasa
driver.get(url)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 440, in get
self.execute(Command.GET, {'url': url})
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 426, in execute
response = self.command_executor.execute(driver_command, params)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 344, in execute
return self._request(command_info[0], url, body=data)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 366, in _request
response = self._conn.request(method, url, body=body, headers=headers)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\request.py", line 78, in request
return self.request_encode_body(
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\request.py", line 170, in request_encode_body
return self.urlopen(method, url, **extra_kw)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\poolmanager.py", line 376, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 813, in urlopen
return self.urlopen(
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 813, in urlopen
return self.urlopen(
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 813, in urlopen
return self.urlopen(
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 785, in urlopen
retries = retries.increment(
File "C:\Users\boxer\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\retry.py", line 592, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=54060): Max retries exceeded with url: /session/9d671bafe2c7f836ad65a632287981ab/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001DD1D339580>: Failed to establish a new connection: [WinError 10061] Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение'))
КОД ТГ БОТА
from asyncio import streams
from inspect import Attribute
from unittest import result
from aiogram import Bot , Dispatcher , executor , types
from aiogram.dispatcher.filters import Text
from aiogram.utils.markdown import hbold , hlink
from bs4 import BeautifulSoup as bs
from fake_useragent import UserAgent
import time
import json
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State , StatesGroup
from config import TOKEN3
import helper_telega
storage = MemoryStorage()
bot = Bot(TOKEN3 ,parse_mode=types.ParseMode.HTML )
dp= Dispatcher(bot , storage=MemoryStorage())
class fsm_serch(StatesGroup):
cheking_steam = State()
back = State()
@dp.message_handler(commands='start')
async def start(message:types.Message):
start_buttons = ['Поиск статистики STEAM']
keyboard= types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add(*start_buttons)
await message.answer('пик', reply_markup=keyboard)
@dp.message_handler(Text(equals='Поиск статистики STEAM'),state=None)
async def Set_Price(message:types.Message):
await fsm_serch.cheking_steam.set()
await message.answer('Вставте ссылку STEAM')
@dp.message_handler(content_types=['text'], state=fsm_serch.cheking_steam)
async def cheking_steam(message:types.Message, state: FSMContext):
global steams
steams = message.text
await message.answer('Записал ссылку STEAM')
time.sleep(3)
helper_telega.starting()
await fsm_serch.next()
from save_card import resultat
await message.answer('Поиск закончил')
card = f'{hbold("Ссылка Faceit: ")}{resultat.get("link_faceit")}\n ' \
f'{hbold("Имя: ")}{resultat.get("account_name")}\n ' \
f'{hbold("steam ID 64: ")}{resultat.get("steam_id64")}\n ' \
f'{hbold("Faceit: ")}{resultat.get("faceit_elo")}\n ' \
f'{hbold("KD: ")}{resultat.get("kd")}\n ' \
f'{hbold("HS: ")}{resultat.get("headshot")}\n ' \
f'{hbold("AVG УРОН: ")}{resultat.get("avg_damage")}\n ' \
f'{hbold("Звание: ")}{resultat.get("ranks")}\n ' \
f'{hbold("Лучшее звание: ")}{resultat.get("best_ranks")}\n ' \
f'{hbold("Лучшее звание: ")}{resultat.get("wins_on_mm")}\n ' \
f'{hbold("Аккаунт TRUST: ")}{resultat.get("account_trust")}\n ' \
f'{hbold("Процент побед: ")}{resultat.get("avg_winrate")}\n ' \
f'{hbold("Странна: ")}{resultat.get("country")}\n ' \
f'{hbold("Аккаунт создан: ")}{resultat.get("account_create")}\n ' \
f'{hbold("Купил CS:GO ")}{resultat.get("account_buy_csgo")}\n ' \
f'{hbold("Часов в CS ")}{resultat.get("hours_on_csgo")}\n ' \
f'{hbold("kd on hltv: ")}{resultat.get("kd_hltv")}\n ' \
f'{hbold("Чаще всего играет с ")}{resultat.get("best_friends")}\n ' \
f'{hbold("Чаще всего играет с ")}{resultat.get("best_friends2")}\n ' \
f'{hbold("Чаще всего играет с ")}{resultat.get("best_friends3")}\n ' \
f'{hbold("Чаще всего играет с ")}{resultat.get("best_friends4")}\n ' \
f'{hbold("Друзья в бане ")}{resultat.get("baned_friend")}\n ' \
f'{hbold("Примерная цена: ")}{resultat.get("steam_price")}\n '
await message.answer(card)
print('fsm завершил')
start_buttons = ['Назад']
keyboard= types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add(*start_buttons)
await message.answer('Нажмите назад для повторного поиска', reply_markup=keyboard)
@dp.message_handler(Text(equals='Назад'),state=fsm_serch.back)
async def back(message:types.Message, state: FSMContext):
start_buttons = ['Поиск статистики STEAM']
keyboard= types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add(*start_buttons)
await message.answer('пик', reply_markup=keyboard)
await state.finish()
def main():
print("Бот запущен")
executor.start_polling(dp)
if __name__ == '__main__':
main()
КОД ГДЕ ВОЗНИКАЕТ ОШИБКА
from selenium import webdriver
from fake_useragent import UserAgent
from selenium_stealth import stealth
import time
import random
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.headless = True
ua = UserAgent()
options.add_argument(f'user-agent={ua.random}')
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r"C:\Users\boxer\Desktop\test\chroma_driver\chromedriver.exe")
stealth(driver,
languages=["en-US", "en"],
vendor="Google Inc.",
platform="Win64",
webgl_vendor="Intel Inc.",
renderer="Intel Iris OpenGL Engine",
fix_hairline=True,
)
def second_phasa():
from steam_checer import steam_id64
global ranks , best_ranks , avg_winrate , avg_damage , headshot , kd_hltv , kd , chance_klath , wins_on_mm
url = f"https://csgostats.gg/player/{steam_id64}"
time.sleep(random.uniform(1.01 , 3.5))
driver.get(url)
time.sleep(random.uniform(13 , 15.5))
try :
wins_on_mm=driver.find_element(By.XPATH ,'//*[@id="competitve-wins"]/span').text
except Exception as ex:
wins_on_mm = 0
try :
ranks = driver.find_element(By.CLASS_NAME , 'player-ranks').find_element(By.TAG_NAME, 'img').get_attribute('src')
ranks = str(ranks).replace('https://static.csgostats.gg/images/ranks/','').replace('.png','')
ranks = int(ranks)
except Exception as ex:
ranks = 33
try:
best_ranks = driver.find_element(By.XPATH, '//*[@id="content-wrapper"]/div[3]/div[1]/div/div[2]/div[1]/div').find_element(By.TAG_NAME, 'img').get_attribute('src')
best_ranks = str(best_ranks).replace('https://static.csgostats.gg/images/ranks/','').replace('.png','')
best_ranks = int(best_ranks)
except Exception as ex:
best_ranks = 33
try:
kd = driver.find_element(By.XPATH, '//*[@id="kpd"]/span').text
except Exception as ex:
kd = 0
try:
kd_hltv = driver.find_element(By.XPATH, '//*[@id="rating"]/span').text
except Exception as ex:
kd_hltv = 0
try:
chance_klath = driver.find_element(By.XPATH, '//*[@id="player-overview"]/div[2]/div/div[1]/div[2]/div[1]/span[2]').text
except Exception as ex:
chance_klath = 0
#прокрутка сайта
js="var q=document.documentElement.scrollTop=350"
driver.execute_script(js)
time.sleep(3)
try:
headshot = driver.find_element(By.XPATH, '//*[@id="player-overview"]/div[1]/div[4]/div/div[2]/div[2]').text
headshot = str(headshot).replace('1', '').strip()
except Exception as ex:
headshot = 0
try:
avg_winrate = driver.find_element(By.XPATH,'//*[@id="player-overview"]/div[1]/div[3]/div/div[2]/div[2]').text
avg_winrate = str(avg_winrate).replace('\n3' , "") .replace('\n2' , "").replace('\n1' , "").replace('\n4' , "").replace('\n5' , "")
except Exception as ex:
avg_winrate = 0
try:
avg_damage = driver.find_element(By.XPATH, '//*[@id="player-overview"]/div[1]/div[5]/div/div[2]/div[2]').text
except Exception as ex:
avg_damage = 0
driver.close()
driver.quit()
#отбор результатов
if ranks == 1:
ranks = 'Silver 1'
elif ranks == 2:
ranks = 'Silver 2'
elif ranks == 3:
ranks = 'Silver 3'
elif ranks == 4:
ranks = 'Silver 4'
elif ranks == 5:
ranks = 'Silver 5'
elif ranks == 6:
ranks = 'Silver 6'
elif ranks == 7:
ranks = 'Gold Nova 1'
elif ranks == 8:
ranks = 'Gold Nova 2'
elif ranks == 9:
ranks = 'Gold Nova 3'
elif ranks == 10:
ranks = 'Gold Nova 4'
elif ranks == 11:
ranks = 'Master Guardian 1'
elif ranks == 12:
ranks = 'Master Guardian 2'
elif ranks == 13:
ranks = 'Master Guardian 3'
elif ranks == 14:
ranks = 'Distinguished Master Guardian'
elif ranks == 15:
ranks = 'Legendary Eagle'
elif ranks == 16:
ranks = 'Legendary Eagle Master'
elif ranks == 17:
ranks = 'Supreme Master First Class'
elif ranks == 18:
ranks = 'The Global Elite'
else :
ranks = 'Неизвестное'
if best_ranks == 1:
best_ranks = 'Silver 1'
elif best_ranks == 2:
best_ranks = 'Silver 2'
elif best_ranks == 3:
best_ranks = 'Silver 3'
elif best_ranks == 4:
best_ranks = 'Silver 4'
elif best_ranks == 5:
best_ranks = 'Silver 5'
elif best_ranks == 6:
best_ranks = 'Silver 6'
elif best_ranks == 7:
best_ranks = 'Gold Nova 1'
elif best_ranks == 8:
best_ranks = 'Gold Nova 2'
elif best_ranks == 9:
best_ranks = 'Gold Nova 3'
elif best_ranks == 10:
best_ranks = 'Gold Nova 4'
elif best_ranks == 11:
best_ranks = 'Master Guardian 1'
elif best_ranks == 12:
best_ranks = 'Master Guardian 2'
elif best_ranks == 13:
best_ranks = 'Master Guardian 3'
elif best_ranks == 14:
best_ranks = 'Distinguished Master Guardian'
elif best_ranks == 15:
best_ranks = 'Legendary Eagle'
elif best_ranks == 16:
best_ranks = 'Legendary Eagle Master'
elif best_ranks == 17:
best_ranks = 'Supreme Master First Class'
elif best_ranks == 18:
best_ranks = 'The Global Elite'
else :
best_ranks = 'Неизвестное'
print("2й этап завершил работу")
from helper_telega import starting3
starting3()