Я искал похожие вопросы на этом форуме, но особой помощи не было.Если кто-то может указать мне на помощь или если этот вопрос является дубликатом, я закрою или отредактирую его.
Сценарий: я пытаюсь автоматизировать процесс входа на веб-сайт.Код иногда работает нормально, входит в систему и закрывает браузер.Но есть несколько ошибок, вызванных отказом urllib3 MaxRetry и Connection, которые приводят к закрытию окна браузера в середине теста.Я пытался использовать time.sleep, но это не помогло.
Вот код, ошибка и трассировка стека.
import sys
import argparse
from selenium import webdriver
import requests
from requests.adapters import HTTPAdapter
import urllib3
from urllib3.util.retry import Retry
import time
parser = argparse.ArgumentParser()
parser.add_argument('browser', default='chrome', help='Types of browser:chrome, firefox, ie')
parser.add_argument('username', help='This is the username')
parser.add_argument('password', help='This is the password')
args = parser.parse_args()
setup_parameters = sys.argv[1:]
class Browser(object):
"""The Login class contains methods to log in to the Premier portal
with the supplied browser, username and password as command line arguments.
The webdriver then waits for the number of seconds specified in the implicit wait method
and finally the quit method closes the browser.
"""
url = 'https:someurl.com'
# Initialization Method
def __init__(self):
self.username = setup_parameters[1]
self.password = setup_parameters[2]
if setup_parameters[0] == 'chrome':
self.browser = webdriver.Chrome()
print("Running tests on Chrome browser")
self.browser.implicitly_wait(15)
self.site_login()
self.site_close()
elif setup_parameters[0] == 'ie':
self.browser = webdriver.Ie()
print("Running tests on Internet Explorer browser")
self.browser.implicitly_wait(15)
self.site_login()
self.site_close()
elif setup_parameters[0] == 'firefox':
self.browser = webdriver.Firefox()
print("Running tests on Firefox browser")
self.browser.implicitly_wait(15)
self.site_login()
self.site_close()
elif setup_parameters[0] == 'None':
print('No browser type specified.... continuing with the default browser')
self.browser = webdriver.Chrome()
# Method used to log in to the site
def site_login(self):
try:
self.browser.get(self.url)
self.browser.find_element_by_id("Username").send_keys(self.username)
self.browser.find_element_by_id("Password").send_keys(self.password)
self.browser.find_element_by_id("btnLogin").click()
time.sleep(30)
except requests.ConnectionError as e:
print("******Connection error encountered! Trying again....")
print(str(e))
time.sleep(10)
except requests.Timeout as e:
print("*****Timeout Error!********")
print(str(e))
except requests.RequestException as e:
time.sleep(30)
print("*******Server rejected the requests, too many requests!*******")
print(str(e))
except KeyboardInterrupt:
print("*********User interruption detected*******")
except ConnectionRefusedError as e:
time.sleep(30)
print(str(e))
print("*********Portal Connection refused by the server**********")
except urllib3.exceptions.NewConnectionError as e:
print(str(e))
print("********Portal New connection timed out***********")
time.sleep(30)
except urllib3.exceptions.MaxRetryError as e:
print(str(e))
time.sleep(30)
print("*********Portal Max tries exceeded************")
except urllib3.exceptions.ConnectTimeoutError as e:
time.sleep(10)
print("**********Timeout error************")
except urllib3.exceptions.ClosedPoolError as e:
time.sleep(10)
print(str(e))
except urllib3.exceptions.HTTPError as e:
time.sleep(10)
print(str(e))
self.browser.maximize_window()
self.browser.implicitly_wait(10)
# Closing the browser window and terminating the test
def site_close(self):
self.browser.quit()
if __name__ == '__main__':
Browser().site_login()
Browser().site_close()
C:\PycharmProjects\PortalAutomation>python Login.py ie 1EADMIN password1
Running tests on Internet Explorer browser
HTTPConnectionPool(host='127.0.0.1', port=62084): Max retries exceeded with url: /session/628678c3-b918-461a-bf41-0deaf16f4317/url (Caused by NewConnectionError('<urllib3.connection.HTT
PConnection object at 0x00000000039C9908>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
*********Portal Max tries exceeded************
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\urllib3\connection.py", line 171, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "C:\Python37\lib\site-packages\urllib3\util\connection.py", line 79, in create_connection
raise err
File "C:\Python37\lib\site-packages\urllib3\util\connection.py", line 69, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
chunked=chunked)
File "C:\Python37\lib\site-packages\urllib3\connectionpool.py", line 354, in _make_request
conn.request(method, url, **httplib_request_kw)
File "C:\Python37\lib\http\client.py", line 1229, in request
self._send_request(method, url, body, headers, encode_chunked)
File "C:\Python37\lib\http\client.py", line 1275, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "C:\Python37\lib\http\client.py", line 1224, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "C:\Python37\lib\http\client.py", line 1016, in _send_output
self.send(msg)
File "C:\Python37\lib\http\client.py", line 956, in send
self.connect()
File "C:\Python37\lib\site-packages\urllib3\connection.py", line 196, in connect
conn = self._new_conn()
File "C:\Python37\lib\site-packages\urllib3\connection.py", line 180, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x00000000039C9FD0>: Failed to establish a new connection: [WinError 10061] No connection could be ma
de because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Login.py", line 110, in <module>
Browser().site_login()
File "Login.py", line 100, in site_login
self.browser.maximize_window()
File "C:\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 736, in maximize_window
self.execute(command, params)
File "C:\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 318, in execute
response = self.command_executor.execute(driver_command, params)
File "C:\Python37\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 375, in execute
return self._request(command_info[0], url, body=data)
File "C:\Python37\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 402, in _request
resp = http.request(method, url, body=body, headers=headers)
File "C:\Python37\lib\site-packages\urllib3\request.py", line 72, in request
**urlopen_kw)
File "C:\Python37\lib\site-packages\urllib3\request.py", line 150, in request_encode_body
return self.urlopen(method, url, **extra_kw)
File "C:\Python37\lib\site-packages\urllib3\poolmanager.py", line 322, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File "C:\Python37\lib\site-packages\urllib3\connectionpool.py", line 667, in urlopen
**response_kw)
File "C:\Python37\lib\site-packages\urllib3\connectionpool.py", line 667, in urlopen
**response_kw)
File "C:\Python37\lib\site-packages\urllib3\connectionpool.py", line 667, in urlopen
**response_kw)
File "C:\Python37\lib\site-packages\urllib3\connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "C:\Python37\lib\site-packages\urllib3\util\retry.py", line 398, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=62084): Max retries exceeded with url: /session/628678c3-b918-461a-bf41-0deaf16f4317/window/maximize (Caused
by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x00000000039C9FD0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the t
arget machine actively refused it'))