Undetected Chromedriver issue when headless is on

Question:

import undetected_chromedriver.v2 as uc
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def main(url):
    options = uc.ChromeOptions()
    options.headless = True
    driver = uc.Chrome(options=options)
    driver.get(url)
    try:
        WebDriverWait(driver, 10).until(
            EC.title_contains(('Reservations'))
        )
        print(driver.title)
    except Exception as e:
        print(type(e).__name__)
    finally:
        driver.quit()


if __name__ == "__main__":
    main('https://www.example.com/')

if headless = True the site isn’t responsive. How can i solve that?

P.S am seeking solution for selenium only.

Answers:

Use a virtual display such as Xvfb so that you don’t need to use headless mode on a headless machine such as Linux servers.

There’s a Selenium Python framework, https://github.com/seleniumbase/SeleniumBase, with built-in integration to undetected-chromedriver for that exact thing. When running your tests, add --uc as a pytest command-line option for your SeleniumBase tests. Eg:

pytest --uc --xvfb

That lets you successfully run Selenium Python tests on a Linux headless machine in undetected-chromedriver mode. (With SeleniumBase)

You can use the following for your test, example.py:

from seleniumbase import BaseCase

class MyTestClass(BaseCase):
    def test_hyatt(self):
        self.open("https://www.example.com/")
        self.assert_in("Reservations", self.get_title())
        print(self.get_title())

Then when running it:

pytest example.py --uc --xvfb
==================== test session starts ====================
platform darwin -- Python 3.10.5, pytest-7.1.3, pluggy-1.0.0
rootdir: /Users/michael/github/SeleniumBase/examples, configfile: pytest.ini
plugins: html-2.0.1, xdist-2.5.0, forked-1.4.0, rerunfailures-10.2, ordering-0.6, cov-3.0.0, metadata-2.0.2, seleniumbase-4.3.8
collected 1 item                                                                                   

example.py Example Domain
.

==================== 1 passed in 8.68s
Answered By: Michael Mintz