UnboundLocalError when using pytest-splinter in Docker container
I am attempting to shift my automation at work from Selenium to Splinter. As part of this, I have chosen to utilize the pytest-selenium plugin for better QOL. Unfortunately, it appears that Splinter is raising an UnboundLocalError when run from a Docker container, not when running from command line. This error is raised at line 68 in browser.py within the Splinter library.
Any thoughts on what could be happening here?
splinter_webdriver = 'chrome', retry_count = 3
def get_browser(splinter_webdriver, retry_count=3):
kwargs = get_args(driver=splinter_webdriver,
download_dir=splinter_file_download_dir,
download_ftypes=splinter_download_file_types,
firefox_pref=splinter_firefox_profile_preferences,
firefox_prof_dir=splinter_firefox_profile_directory,
remote_url=splinter_remote_url,
executable=splinter_webdriver_executable,
headless=splinter_headless,
driver_kwargs=splinter_driver_kwargs)
try:
return splinter_browser_class(
splinter_webdriver, visit_condition=splinter_browser_load_condition,
visit_condition_timeout=splinter_browser_load_timeout,
> wait_time=splinter_wait_time, **kwargs
)
/usr/local/lib/python3.6/site-packages/pytest_splinter/plugin.py:517:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
args = ('chrome',), kwargs = {'headless': True, 'wait_time': 5}
visit_condition = <function splinter_browser_load_condition.<locals>.<lambda> at 0x7ff49aaaf048>
visit_condition_timeout = 10
def Browser(*args, **kwargs):
"""Emulate splinter's Browser."""
visit_condition = kwargs.pop('visit_condition')
visit_condition_timeout = kwargs.pop('visit_condition_timeout')
> browser = splinter.Browser(*args, **kwargs)
/usr/local/lib/python3.6/site-packages/pytest_splinter/plugin.py:72:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
driver_name = 'chrome', retry_count = 3, args = ()
kwargs = {'headless': True, 'wait_time': 5}
driver = <class 'splinter.driver.webdriver.chrome.WebDriver'>
def Browser(driver_name="firefox", retry_count=3, *args, **kwargs):
"""
Returns a driver instance for the given name.
When working with ``firefox``, it's possible to provide a profile name
and a list of extensions.
If you don't provide any driver_name, then ``firefox`` will be used.
If there is no driver registered with the provided ``driver_name``, this
function will raise a :class:`splinter.exceptions.DriverNotFoundError`
exception.
"""
try:
driver = _DRIVERS[driver_name]
except KeyError:
raise DriverNotFoundError("No driver for %s" % driver_name)
> return get_driver(driver, *args, **kwargs)
/usr/local/lib/python3.6/site-packages/splinter/browser.py:90:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
driver = <class 'splinter.driver.webdriver.chrome.WebDriver'>, retry_count = 3
args = (), kwargs = {'headless': True, 'wait_time': 5}, _ = 2
def get_driver(driver, retry_count=3, *args, **kwargs):
"""Try to instantiate the driver.
Common selenium errors are caught and a retry attempt occurs.
This can mitigate issues running on Remote WebDriver.
"""
for _ in range(retry_count):
try:
return driver(*args, **kwargs)
except (IOError, HTTPException, WebDriverException, MaxRetryError) as e:
pass
> raise e
E UnboundLocalError: local variable 'e' referenced before assignment
/usr/local/lib/python3.6/site-packages/splinter/browser.py:68: UnboundLocalError
Dockerfile I am using:
FROM python:3.6-slim-buster
# Set working directory
WORKDIR /python/tests/automation/
# Install third-party dependencies
RUN pip install pipenv
COPY Pipfile .
COPY Pipfile.lock .
RUN pipenv install --system --deploy --ignore-pipfile
# Copy automation data and configuration
COPY . .
# Clear .pyc files for conftest.py import
RUN find . -name *.pyc -delete
# Install Google Chrome
RUN apt-get update && \
apt-get install -y wget dpkg && \
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \
dpkg -i google-chrome-stable_current_amd64.deb; apt-get -fy install
RUN webdriverdownloader chrome
RUN pytest -m splinter
To add some additional context, this only occurs when using either pytest-splinter or Splinter within a Docker container.
Running pytest-selenium or Selenium with the above Docker set up does not error out.
Feel free to contact me for any additional information I can provide.
@jmt-transloc If you switch from the 0.13.0 release of splinter to the master branch, the error you're getting will be raised correctly. This will make debugging this issue easier.
@jmt-transloc If you switch from the 0.13.0 release of splinter to the master branch, the error you're getting will be raised correctly. This will make debugging this issue easier.
Thanks for your reply! I'll give that a shot and report back.
Hello,
I'm having troubles trying to run in a Docker container too. I'm using an Alpine 3.11 based container, with chromium and chromedriver installed.
I launch the browser like this :
import logging
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from splinter import Browser
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.DEBUG)
logger = logging.getLogger(__name__)
opts = Options()
opts.add_argument("--disable-gpu")
opts.add_argument("--no-sandbox")
opts.add_argument("--disable-setuid-sandbox")
opts.add_argument("--disable-software-rasterizer")
opts.add_argument('--start-maximized')
logging.info('Trying to start Chromium via Chromedriver ...')
with Browser('chrome', headless=True) as browser:
browser.driver = webdriver.Chrome('/usr/bin/chromedriver', chrome_options=opts)
browser.visit('https://google.com')
logging.info('Hello Chromium !')
and it always fail with the following error :
2020-02-13 06:33:43,220 - root - INFO - Trying to start Chromium via Chromedriver ...
2020-02-13 06:33:44,225 - selenium.webdriver.remote.remote_connection - DEBUG - POST http://127.0.0.1:34645/session {"capabilities": {"firstMatch": [{}], "alwaysMatch": {"browserName": "chrome", "platformName": "any", "goog:chromeOptions": {"extensions": [], "args": ["--headless", "--disable-gpu"]}}}, "desiredCapabilities": {"browserName": "chrome", "version": "", "platform": "ANY", "goog:chromeOptions": {"extensions": [], "args": ["--headless", "--disable-gpu"]}}}
2020-02-13 06:33:44,226 - urllib3.connectionpool - DEBUG - Starting new HTTP connection (1): 127.0.0.1:34645
2020-02-13 06:33:44,280 - urllib3.connectionpool - DEBUG - http://127.0.0.1:34645 "POST /session HTTP/1.1" 500 324
2020-02-13 06:33:44,281 - selenium.webdriver.remote.remote_connection - DEBUG - Finished Request
2020-02-13 06:33:45,292 - selenium.webdriver.remote.remote_connection - DEBUG - POST http://127.0.0.1:56305/session {"capabilities": {"firstMatch": [{}], "alwaysMatch": {"browserName": "chrome", "platformName": "any", "goog:chromeOptions": {"extensions": [], "args": ["--headless", "--disable-gpu"]}}}, "desiredCapabilities": {"browserName": "chrome", "version": "", "platform": "ANY", "goog:chromeOptions": {"extensions": [], "args": ["--headless", "--disable-gpu"]}}}
2020-02-13 06:33:45,293 - urllib3.connectionpool - DEBUG - Starting new HTTP connection (1): 127.0.0.1:56305
2020-02-13 06:33:45,347 - urllib3.connectionpool - DEBUG - http://127.0.0.1:56305 "POST /session HTTP/1.1" 500 324
2020-02-13 06:33:45,347 - selenium.webdriver.remote.remote_connection - DEBUG - Finished Request
2020-02-13 06:33:46,352 - selenium.webdriver.remote.remote_connection - DEBUG - POST http://127.0.0.1:46041/session {"capabilities": {"firstMatch": [{}], "alwaysMatch": {"browserName": "chrome", "platformName": "any", "goog:chromeOptions": {"extensions": [], "args": ["--headless", "--disable-gpu"]}}}, "desiredCapabilities": {"browserName": "chrome", "version": "", "platform": "ANY", "goog:chromeOptions": {"extensions": [], "args": ["--headless", "--disable-gpu"]}}}
2020-02-13 06:33:46,353 - urllib3.connectionpool - DEBUG - Starting new HTTP connection (1): 127.0.0.1:46041
2020-02-13 06:33:46,406 - urllib3.connectionpool - DEBUG - http://127.0.0.1:46041 "POST /session HTTP/1.1" 500 324
2020-02-13 06:33:46,406 - selenium.webdriver.remote.remote_connection - DEBUG - Finished Request
Traceback (most recent call last):
File "./plop/simple.py", line 24, in <module>
with Browser('chrome', headless=True) as browser:
File "/usr/lib/python3.8/site-packages/splinter/browser.py", line 92, in Browser
return get_driver(driver, *args, **kwargs)
File "/usr/lib/python3.8/site-packages/splinter/browser.py", line 70, in get_driver
raise err
File "/usr/lib/python3.8/site-packages/splinter/browser.py", line 66, in get_driver
return driver(*args, **kwargs)
File "/usr/lib/python3.8/site-packages/splinter/driver/webdriver/chrome.py", line 43, in __init__
self.driver = Chrome(options=options, **kwargs)
File "/usr/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py", line 76, in __init__
RemoteWebDriver.__init__(
File "/usr/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
self.start_session(capabilities, browser_profile)
File "/usr/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/usr/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /usr/lib/chromium/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
I'm using splinter Github master version, installed with :
python -m pip install --upgrade "git+https://github.com/cobrateam/splinter.git"
However, if I start chromium with the following command line in a container's shell, it works fine and I get the web page output on the console :
/usr/bin/chromium-browser --headless --disable-gpu --no-sandbox --disable-setuid-sandbox --disable-software-rasterizer --start-maximized --dump-dom https://google.com
What am I doing wrong ?
Ok just found my mistake.
Selenium Chromedriver options was no correctly set, with the following code it works fine :
import logging
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from splinter import Browser
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.DEBUG)
logger = logging.getLogger(__name__)
opts = Options()
opts.add_argument("--no-sandbox")
opts.add_argument("--disable-setuid-sandbox")
opts.add_argument("--disable-software-rasterizer")
opts.add_argument('--start-maximized')
logging.info('Trying to start Chromium via Chromedriver ...')
selenium_opts = {'options': opts}
with Browser('chrome', headless=True, **selenium_opts) as browser:
browser.visit('https://google.com')
logging.info('Hello Chromium !')
Sorry for the noise :disappointed:
Going to close this out as my team and I decided to not move forward with Splinter.