Issue with custom profile selection and Selenium headless compatibility

Here is the code snippet I am currently using - and yes, I have tried to keep it short and concise.

import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

import bs4

options=Options()
#options.add_argument('--headless') # Works while not headless?
options.add_argument('--disable-gpu')  # Last I checked this was necessary.
options.add_argument("--user-data-dir=profiles\\") #Keeps login data
options.add_argument("--profile-directory=Profile 1")

driver=webdriver.Chrome(chrome_options=options)
driver.get("http://www.google.com")
html=driver.page_source
soup=bs4.BeautifulSoup(html, "html.parser")

print(soup)

The main issue arises from the --user-data-dir and --profile-directory parameters. In my testing scenario, a custom chrome profile (usually located at

C:\Users\User\AppData\Local\Google\Chrome\User Data
) is placed in the current directory to keep it separate from any existing chrome sessions.

If the --headless parameter is activated with the above parameters, the driver hangs (the CMD window stays open and no output is displayed on the Python command line). However, without enabling it, the window pops up and functions properly.

Nevertheless, --headless does function when using any profile within the default directory mentioned earlier.

This is the console output:

[0120/222514.611:ERROR:gpu_process_transport_factory.cc(967)] Lost UI shared context.

DevTools listening on ws://127.0.0.1:59961/devtools/browser/ee317ed6-93c7-47c2-b26d-63647980ba0d
[0120/222514.619:ERROR:devtools_http_handler.cc(289)] Error writing DevTools active port to file
[0120/222514.624:ERROR:cache_util_win.cc(19)] Unable to move the cache: 0
[0120/222514.625:ERROR:cache_util.cc(140)] Unable to move cache folder profiles\Default\GPUCache to profiles\Default\old_GPUCache_000
[0120/222514.625:ERROR:disk_cache.cc(184)] Unable to create cache
[0120/222514.625:ERROR:shader_disk_cache.cc(622)] Shader Cache Creation failed: -2

It seems like Chromium is assuming that I am using the Default profile even though I explicitly specify that I am not.

Any suggestions would be greatly appreciated. Thank you!

Answer №1

After making a slight adjustment, I was able to successfully run your code with the additional option below:

options.add_argument('--remote-debugging-port=45447')

Prior to adding this option, the code would hang for about a minute before encountering the following error message:

WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist

A helpful comment provided some insight into resolving the issue:

By setting --remote-debugging-port=0 for Chrome, devtools will automatically assign a port and save it as a file called "DevToolsActivePort" in chrome::DIR_USER_DATA.

In summary, once the port is specified with a value other than 0, there is no need to check for the existence of the DevToolsActivePort file. For more details on this discovery, refer to the complete comment and bug report here: chromedriver bug

I hope this explanation proves beneficial!

Answer №2

To resolve the issue, I successfully fixed it by shutting down the command prompt and relaunching it in administrator mode (simply right-click on cmd.exe and select Run as administrator).

No other methods were effective in solving the problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Python script for extracting OTP from Twilio SMS

Currently, I am diving into a web automation project using the selenium python-pytest framework. The challenge I'm facing involves the generation of an OTP after entering my phone number, which then needs to be retrieved and inputted into a text box o ...

Python game where snake refuses to eat food

During code execution, when the snake and food coordinates are identical, the expected behavior is to delete the food item, increase the score by 1, add another square to the snake, and create a new food object. However, the `if` statement in the `next_t ...

It appears that the :first / :first-child selector is not functioning properly with Selenium 2

During my transition from Selenium 1 to Selenium 2, I encountered an issue. The structure I currently have is similar to the following: <ul id="documentType"> <li><a href="http://somelink.com">first</a></li> <li& ...

What is the process for defining the path while utilizing pdb within emacs?

Trying to utilize pdb in emacs, I encountered the need to adjust the path to PYTHONPATH=lib. However, upon entering the command Run pdb (like this): PYTHONPATH=lib pdb ./pychess. I received an error from Emacs stating that the file PYTHONPATH=lib could n ...

What could be the root cause of this AttributeError?

After extensive searching for a solution, I have not been able to find one. Here is the code I am working with: class snakeGame: def _init_(self): pygame.init() self._isRunning = False self._surface = None self.drawList ...

What are some ways to implement parametrization in Selenium IDE?

Attempting to test a login page through Selenium IDE has presented itself as a challenge. Despite manually testing various login values, the most optimal method for fully testing this scenario remains unclear. What approach should I take to effectively t ...

Sorting a collection of objects with version strings using the LooseVersion method

I have a Version class that has a property called version_number which is a string. I can retrieve and sort this list of strings using the following code: sorted_versions = [v.version_number for v in self.version_set] sorted_versions.sort(key=LooseVersion ...

Is it possible to target a specific element within one of two classes that share the same name using CSS or XPath in Webdriver.IO?

Currently, I am using Webdriver.io and facing a challenge in selecting an element within the "text-fields-container" class. This particular element happens to be a password field, and both classes share the same name. Can someone guide me on how to go abou ...

Is there a way to execute automated selenium tests using TFS build 2015?

My NUnit selenium tests are integrated into Unit test and they work perfectly fine when run locally, but not on the TFS Server. After enabling code coverage, I noticed that "Module unittests.dll" was covering most of the code, while "Seleniumtest.exe" had ...

Troublesome behavior exhibited by Numpy's einsum. How to catch it?

When numpy einsum throws the error shown below, what is usually the underlying issue? Traceback (most recent call last): File "rmse_iter.py", line 30, in <module> rmse_out = np.sqrt(np.einsum('ij,ij->i',diffs,diffs)/3.0) TypeError ...

Troubleshooting issue with CSS SVG Clip path functionality - facing technical difficulties

Having an issue with a clip path in my CSS. When I apply the clip path to my CSS fill, the image isn't showing up... I'm using Chrome. Any ideas on how to fix this? I found this helpful generator https://example.com .card .content .picture img { ...

Incorporate the git commit hash into a Python file during installation

Is there a way to automatically embed the git hash into the version number of a python module when it is installed from a git repository using ./setup.py install? How can this be done? I am considering defining a function in setup.py that will add the has ...

NoseTest uncovers testing failures with Magic Mock

Currently, I am utilizing MagicMock for testing a function within a web application. This function is directly imported from a module. The expected functionality is as follows: when the tested function is called, it triggers a third-party API (although th ...

Tips on analyzing two lists that have unique identifiers yet contain identical information

I am dealing with 2 lists that have the same content but reference different names. There is a table I can download with an 'Export' button, which saves a CSV file to my local system. I am using Selenium to retrieve the table data and I have att ...

Uncovering the Magic of Outer Joins in Django's ORM

Currently, I have two models within my Project. class Blog(models.Model): title=models.CharField(max_length=20, blank=False, default='') content=models.CharField(max_length=2000, blank=False, default='') class UserLikedBlog ...

Extract HTML href links that correspond to a specific string from a given list of strings using Beautiful Soup

I am currently working on extracting specific URLs from a webpage that contains a list of various links. My goal is to only retrieve the URLs that match certain strings in a predetermined list. These strings are a subset of the text found within the links ...

The Submit button cannot be selected in the SelectField

I keep encountering a "Method Not Allowed" error when I select data from a dropdown field and click on the 'Choose' button to submit. What could be causing this issue? app.py from flask import Flask, render_template, flash from flask_wtf import ...

Extracting data from SVG files using Python

Is there a way to extract coordinates/paths from an SVG file using python (I think it's located under the "path" ID, specifically the d="..."/>) for use in controlling a 2 axis CNC machine? I've looked on various platforms like SO and Google for ...

Optimizing Google e2e testing using Protractor

Improving login efficiency is necessary to enhance the speed of executing e2e tests. At present, after every test, the Chrome browser shuts down, requiring a new login session for each subsequent test. What changes can be made to address this issue? Any ...

The steps for changing instances in WebDriver

Hello, I currently have a setup with my framework that involves the following: ClassA { // This class receives Selenium WebDriver calls through the 'driver' object reference to interact with UI elements public WebDriver get() { ...