Launch chrome browser - selenium-webdriver

I am trying to launch chrome browser (version 26.0) using webdriver.
I am getting the following error message.
Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver.
at com.google.common.base.Preconditions.checkState(Preconditions.java:176)
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:105)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:69)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:107)
at googleSearch.main(googleSearch.java:13)
Code I used:
driver = new ChromeDriver();
driver.navigate().to("http://www.google.com/");
I use mac 10.8.2.

For this to work, you need to:
Install Chrome
Install Chrome Web Driver
Make sure you have the chrome web driver in you path, for example on Windows something pointing to chromedriver2_win32_0.8. You can put that in your path by either: (a) Modifying your windows path environment variable, or; (b) adding the following to your java command line options:
-Dwebdriver.chrome.driver='/path/to/driver'
In case of using selenium grid
-Dwebdriver.chrome.driver='/path/to/driver'
has to be added while creating a node from command line.

1) In case of using selenium without GRID:
System.setProperty("webdriver.chrome.driver","/absolute/path/to/chromedriver");
driver = new ChromeDriver();
does the job.
2) In case of using selenium with GRID:
System.setProperty("webdriver.chrome.driver","/absolute/path/to/chromedriver");
driver = new ChromeDriver();
And from command line, while creating a node for chrome browser one needs to pass
-Dwebdriver.chrome.driver='/absolute/path/to/chromedriver'
The above two changes did the job for me, apart from this I was getting this libnss3.so not found error which I solved by creating a symlink of libnss3.so present in /usr/lib/x86_64-linux-gnu/ folder to /usr/lib/
ln -s /usr/lib/x86_64-linux-gnu/libnss3.so /usr/lib/libnss3.so
PS: Also make sure that you are using 64bit OR 32bit version of chrome driver as per your system.

For chrome to work with selenium-webdriver you need to have not only a working chrome browser installed, but also the chromedriver executable. Note that these are TWO different executable files that both need to be specified.

change the permission of file and then run your code again.
Open command prompt and navigate to directory where your chrome exe exists and write
chmod 777 filename
Hope it will solve your problem.

Related

Robot Framework Open Browser and Create WebDriver not working after Updates [duplicate]

Recently I switched computers and since then I can't launch chrome with selenium. I've also tried Firefox but the browser instance just doesn't launch.
from selenium import webdriver
d = webdriver.Chrome('/home/PycharmProjects/chromedriver')
d.get('https://www.google.nl/')
i get the following error:
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
(Driver info: chromedriver=2.43.600233, platform=Linux 4.15.0-38-generic x86_64)
i have the latest chrome version and chromedriver installed
EDIT:
After trying #b0sss solution i am getting the following error.
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
(chrome not reachable)
(The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so chromedriver is assuming that Chrome has crashed.)
(Driver info: chromedriver=2.43.600233 (523efee95e3d68b8719b3a1c83051aa63aa6b10d),platform=Linux 4.15.0-38-generic x86_64)
Try to download HERE and use this latest chrome driver version:
https://sites.google.com/chromium.org/driver/
Try this:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
d = webdriver.Chrome('/home/<user>/chromedriver',chrome_options=chrome_options)
d.get('https://www.google.nl/')
This error message...
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
...implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.
Your main issue is the Chrome browser is not installed at the default location within your system.
The server i.e. ChromeDriver expects you to have Chrome installed in the default location for each system as per the image below:
1For Linux systems, the ChromeDriver expects /usr/bin/google-chrome to be a symlink to the actual Chrome binary.
Solution
In case you are using a Chrome executable in a non-standard location you have to override the Chrome binary location as follows:
Python Solution:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.binary_location = "C:\\path\\to\\chrome.exe" #chrome binary location specified here
options.add_argument("--start-maximized") #open Browser in maximized mode
options.add_argument("--no-sandbox") #bypass OS security model
options.add_argument("--disable-dev-shm-usage") #overcome limited resource problems
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
driver.get('http://google.com/')
Java Solution:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions opt = new ChromeOptions();
opt.setBinary("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"); //chrome binary location specified here
options.addArguments("start-maximized");
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
WebDriver driver = new ChromeDriver(opt);
driver.get("https://www.google.com/");
hope this helps someone. this worked for me on Ubuntu 18.10
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver', options=chrome_options)
driver.get('http://www.google.com')
print('test')
driver.close()
I encountered the exact problem running on docker container (in build environment). After ssh into the container, I tried running the test manually and still encountered
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /usr/bin/google-chrome-stable is
no longer running, so ChromeDriver is assuming that Chrome has crashed.)
When I tried running chrome locally /usr/bin/google-chrome-stable, error message
Running as root without --no-sandbox is not supported
I checked my ChromeOptions and it was missing --no-sandbox, which is why it couldn't spawn chrome.
capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
chromeOptions: { args: %w(headless --no-sandbox disable-gpu window-size=1920,1080) }
)
I had a similar issue, and discovered that option arguments must be in a certain order. I am only aware of the two arguments that were required to get this working on my Ubuntu 18 machine. This sample code worked on my end:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
d = webdriver.Chrome(executable_path=r'/home/PycharmProjects/chromedriver', chrome_options=options)
d.get('https://www.google.nl/')
For RobotFramework
I solved it! using --no-sandbox
${chrome_options}= Evaluate sys.modules['selenium.webdriver'].ChromeOptions() sys, selenium.webdriver
Call Method ${chrome_options} add_argument test-type
Call Method ${chrome_options} add_argument --disable-extensions
Call Method ${chrome_options} add_argument --headless
Call Method ${chrome_options} add_argument --disable-gpu
Call Method ${chrome_options} add_argument --no-sandbox
Create Webdriver Chrome chrome_options=${chrome_options}
Instead of
Open Browser about:blank headlesschrome
Open Browser about:blank chrome
Assuming that you already downloaded chromeDriver, this error is also occurs when already multiple chrome tabs are open.
If you close all tabs and run again, the error should clear up.
in my case, the error was with www-data user but not with normal user on development. The error was a problem to initialize an x display for this user. So, the problem was resolved running my selenium test without opening a browser window, headless:
opts.set_headless(True)
A simple solution that no one else has said but worked for me was not running without sudo or not as root.
The solutions that every body provide here is good for Clear the face of the issue but
All you need to solve this problem is that You have to run The App on non-root user
on linux.
According to this post
https://github.com/paralelo14/google_explorer/issues/2#issuecomment-246476321
I had the same problem but it was solved just by reinstalling chrome again with the commands below:
$ wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
$ sudo apt install ./google-chrome-stable_current_amd64.deb
This error has been happening randomly during my test runs over the last six months (still happens with Chrome 76 and Chromedriver 76) and only on Linux. On average one of every few hundred tests would fail, then the next test would run fine.
Unable to resolve the issue, in Python I wrapped the driver = webdriver.Chrome() in a try..except block in setUp() in my test case class that all my tests are derived from. If it hits the Webdriver exception it waits ten seconds and tries again.
It solved the issue I was having; not elegantly but it works.
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
try:
self.driver = webdriver.Chrome(chrome_options=chrome_options, desired_capabilities=capabilities)
except WebDriverException as e:
print("\nChrome crashed on launch:")
print(e)
print("Trying again in 10 seconds..")
sleep(10)
self.driver = webdriver.Chrome(chrome_options=chrome_options, desired_capabilities=capabilities)
print("Success!\n")
except Exception as e:
raise Exception(e)
I came across this error on linux environment. If not using headless then you will need
from sys import platform
if platform != 'win32':
from pyvirtualdisplay import Display
display = Display(visible=0, size=(800, 600))
display.start()
Faced with this issue trying to run/debug Python Selenium script inside WSL2 using Pycharm debugger.
First solution was to use --headless mode, but I prefer to have Chrome GUI during the debug process.
In the system terminal outside Pycharm debugger Chrome GUI worked nice with DISPLAY env variable set this way (followed guide here):
export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2; exit;}'):0.0
Unfortunately ~/.bashrc is not running in Pycharm during the debug, export is not working.
The way I've got Chrome GUI worked from Pycharm debugger: run echo $DISPLAY in WSL2, paste ip (you've got something similar to this) 172.18.144.1:0 into Pycharm Debug Configuration > Environment Variables:
Just do not run the script as the root user (in my case).
i had same problem. I was run it on terminal with "sudo geany", you should run it without "sudo" just type on terminal "geany" and it is solved for me.
i faced the same problem but i solved it by moving the chromedriver to this path
'/opt/google/chrome/'
and this code works correctly
from selenium.webdriver import Chrome
driver = Chrome('/opt/google/chrome/chromedrive')
driver.get('https://google.com')
In my case, chrome was broken. following two lines fixed the issue,
apt -y update; apt -y upgrade; apt -y dist-upgrade
apt --fix-broken install
Fixed it buy killing all the chrome processeses running in the remote server before running my script.
That may explain why some answers that recommend you run your script as root works.
$ pkill -9 chrome
$ ./my_script.py
Maybe when you where developing in local, you used options.headless=False in order to see what is the browser doing but you forgot to change it to True in the vm.
For me, the root issue was that the google-chrome/chromedriver version were not compatible with the Selenium version.
Seleniumn and Chrome were working fine until a few days ago and I started getting this missing DevToolsActivePort issue. After trying all sorts of solutions on this thread, it finally occurred to me that the Chrome version might not be compatible with the Selenium version.
Versions at the time of the initial error:
# Below combo does NOT work
Python 3.7.3
selenium==3.141.0
Google Chrome 110.0.5481.77
ChromeDriver 110.0.5481.77
I then downgraded Chrome and ChromeDriver to 109.0.5414.74 but still faced the same error. I checked the versions on a different machine and saw that this combo worked:
# Below combo works
Python 3.7.6
selenium==3.141.0
Google Chrome 80.0.3987.100
ChromeDriver 80.0.3987.16
However, I wasn't able to find a download for Google Chrome V80. This comment had a download to V97 so that's the version I went with. There might be higher versions of Google Chrome that do work but after spending so many days fixing this, I was eager to move onto something else.
sudo apt-get purge google-chrome-stable
sudo wget http://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_97.0.4692.71-1_amd64.deb && \
sudo dpkg -i google-chrome-stable_97.0.4692.71-1_amd64.deb && \
sudo apt-mark hold google-chrome-stable
wget https://chromedriver.storage.googleapis.com/97.0.4692.71/chromedriver_linux64.zip
sudo unzip chromedriver_linux64.zip chromedriver -d /usr/local/bin
After that, my Selenium calls were able to work again. The final version combo:
# Below combo works
Python 3.7.3
selenium==3.141.0
ChromeDriver 97.0.4692.71
Google Chrome 97.0.4692.71
Make sure that both the chromedriver and google-chrome executable have execute permissions
sudo chmod -x "/usr/bin/chromedriver"
sudo chmod -x "/usr/bin/google-chrome"

I tried to invoke chrome from selenium. The browser is getting open but no data is loaded [duplicate]

I am trying to launch chrome with an URL, the browser launches and it does nothing after that.
I am seeing the below error after 1 minute:
Unable to open browser with url: 'https://www.google.com' (Root cause: org.openqa.selenium.WebDriverException: unknown error: DevToolsActivePort file doesn't exist
(Driver info: chromedriver=2.39.562718 (9a2698cba08cf5a471a29d30c8b3e12becabb0e9),platform=Windows NT 10.0.15063 x86_64) (WARNING: The server did not provide any stacktrace information)
My configuration:
Chrome : 66
ChromeBrowser : 2.39.56
P.S everything works fine in Firefox
Thumb rule
A common cause for Chrome to crash during startup is running Chrome as root user (administrator) on Linux. While it is possible to work around this issue by passing --no-sandbox flag when creating your WebDriver session, such a configuration is unsupported and highly discouraged. You need to configure your environment to run Chrome as a regular user instead.
This error message...
org.openqa.selenium.WebDriverException: unknown error: DevToolsActivePort file doesn't exist
...implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.
Your code trials and the versioning information of all the binaries would have given us some hint about what's going wrong.
However as per Add --disable-dev-shm-usage to default launch flags seems adding the argument --disable-dev-shm-usage will temporary solve the issue.
If you desire to initiate/span a new Chrome Browser session you can use the following solution:
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized"); // open Browser in maximized mode
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-gpu"); // applicable to windows os only
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox"); // Bypass OS security model
WebDriver driver = new ChromeDriver(options);
driver.get("https://google.com");
disable-dev-shm-usage
As per base_switches.cc disable-dev-shm-usage seems to be valid only on Linux OS:
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
// The /dev/shm partition is too small in certain VM environments, causing
// Chrome to fail or crash (see http://crbug.com/715363). Use this flag to
// work-around this issue (a temporary directory will always be used to create
// anonymous shared memory files).
const char kDisableDevShmUsage[] = "disable-dev-shm-usage";
#endif
In the discussion Add an option to use /tmp instead of /dev/shm David mentions:
I think it would depend on how are /dev/shm and /tmp mounted.
If they are both mounted as tmpfs I'm assuming there won't be any difference.
if for some reason /tmp is not mapped as tmpfs (and I think is mapped as tmpfs by default by systemd), chrome shared memory management always maps files into memory when creating an anonymous shared files, so even in that case shouldn't be much difference. I guess you could force telemetry tests with the flag enabled and see how it goes.
As for why not use by default, it was a pushed back by the shared memory team, I guess it makes sense it should be useing /dev/shm for shared memory by default.
Ultimately all this should be moving to use memfd_create, but I don't think that's going to happen any time soon, since it will require refactoring Chrome memory management significantly.
Reference
You can find a couple of detailed discussions in:
unknown error: DevToolsActivePort file doesn't exist error while executing Selenium UI test cases on ubuntu
Tests fail immediately with unknown error: DevToolsActivePort file doesn't exist when running Selenium grid through systemd
Outro
Here is the link to the Sandbox story.
I started seeing this problem on Monday 2018-06-04. Our tests run each weekday. It appears that the only thing that changed was the google-chrome version (which had been updated to current) JVM and Selenium were recent versions on Linux box ( Java 1.8.0_151, selenium 3.12.0, google-chrome 67.0.3396.62, and xvfb-run).
Specifically adding the arguments "--no-sandbox" and "--disable-dev-shm-usage" stopped the error.
I'll look into these issues to find more info about the effect, and other questions as in what triggered google-chrome to update.
ChromeOptions options = new ChromeOptions();
...
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
We were having the same issues on our jenkins slaves (linux machine) and tried all the options above.
The only thing helped is setting the argument
chrome_options.add_argument('--headless')
But when we investigated further, noticed that XVFB screen doesn't started property and thats causing this error. After we fix XVFB screen, it resolved the issue.
I had the same problem in python. The above helped. Here is what I used in python -
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('/path/to/your_chrome_driver_dir/chromedriver',chrome_options=chrome_options)
I was facing the same issue recently and after some trial and error it worked for me as well.
MUST BE ON TOP:
options.addArguments("--no-sandbox"); //has to be the very first option
BaseSeleniumTests.java
public abstract class BaseSeleniumTests {
private static final String CHROMEDRIVER_EXE = "chromedriver.exe";
private static final String IEDRIVER_EXE = "IEDriverServer.exe";
private static final String FFDRIVER_EXE = "geckodriver.exe";
protected WebDriver driver;
#Before
public void setUp() {
loadChromeDriver();
}
#After
public void tearDown() {
if (driver != null) {
driver.close();
driver.quit();
}
}
private void loadChromeDriver() {
ClassLoader classLoader = getClass().getClassLoader();
String filePath = classLoader.getResource(CHROMEDRIVER_EXE).getFile();
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeDriverService service = new ChromeDriverService.Builder()
.usingDriverExecutable(new File(filePath))
.build();
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox"); // Bypass OS security model, MUST BE THE VERY FIRST OPTION
options.addArguments("--headless");
options.setExperimentalOption("useAutomationExtension", false);
options.addArguments("start-maximized"); // open Browser in maximized mode
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-gpu"); // applicable to windows os only
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.merge(capabilities);
this.driver = new ChromeDriver(service, options);
}
}
GoogleSearchPageTraditionalSeleniumTests.java
#RunWith(SpringRunner.class)
#SpringBootTest
public class GoogleSearchPageTraditionalSeleniumTests extends BaseSeleniumTests {
#Test
public void getSearchPage() {
this.driver.get("https://www.google.com");
WebElement element = this.driver.findElement(By.name("q"));
assertNotNull(element);
}
}
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
In my case in the following environment:
Windows 10
Python 3.7.5
Google Chrome version 80 and corresponding ChromeDriver in the path C:\Windows
selenium 3.141.0
I needed to add the arguments --no-sandbox and --remote-debugging-port=9222 to the ChromeOptions object and run the code as administrator user by lunching the Powershell/cmd as administrator.
Here is the related piece of code:
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('--disable-infobars')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')
options.add_argument('--remote-debugging-port=9222')
driver = webdriver.Chrome(options=options)
I ran into this problem on Ubuntu 20 with Python Selenium after first downloading the chromedriver separately and then using sudo apt install chromium-browser Even though they were the same version this kept happening.
My fix was to use the provided chrome driver that came with the repo package located at
/snap/bin/chromium.chromedriver
driver = webdriver.Chrome(chrome_options=options, executable_path='/snap/bin/chromium.chromedriver')
Update:
I am able to get through the issue and now I am able to access the chrome with desired url.
Results of trying the provided solutions:
I tried all the settings as provided above but I was unable to resolve the issue
Explanation regarding the issue:
As per my observation DevToolsActivePort file doesn't exist is caused when chrome is unable to find its reference in scoped_dirXXXXX folder.
Steps taken to solve the issue
I have killed all the chrome processes and chrome driver processes.
Added the below code to invoke the chrome
System.setProperty("webdriver.chrome.driver","pathto\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("useAutomationExtension", false);
WebDriver driver = new ChromeDriver(options);
driver.get(url);
Using the above steps I was able to resolve the issue.
Thanks for your answers.
In my case it was problem with CI Agent account on ubuntu server, I solved this using custom --user-data-dir
chrome_options.add_argument('--user-data-dir=~/.config/google-chrome')
My account used by CI Agent didn't have necessary permissions, what was interesting everything was working on root account
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--profile-directory=Default')
chrome_options.add_argument('--user-data-dir=~/.config/google-chrome')
driver = webdriver.Chrome(options=chrome_options)
url = 'https://www.google.com'
driver.get(url)
get_url = driver.current_url
print(get_url)
There is lot of possible reasons for the RESPONSE InitSession ERROR unknown error: DevToolsActivePort file doesn't exist error message (as we can see from the number of answers for this question). So let's dive deeper to explain what exactly this error message means.
According to chromedriver source code the message is created in ParseDevToolsActivePortFile method. This method is called from the loop after launching chrome process.
In the loop the driver check if the chrome process is still running and if the ParseDevToolsActivePortFile file was already created by chrome. There is a hardcoded 60s timeout for this loop.
I see two possible reasons for this message:
Chrome is really slow during startup - for example due to lack of system resources - mainly CPU or memory. In this case it can happen that sometimes chrome manage to start in time limit and sometimes not.
There is another issue which prevents chrome to start - missing or broken dependency, wrong configuration etc. In such case this error message is not really helpful and you should find another log message which explain the true reason of the failure.
It happens when chromedriver fails to figure out what debugging port chrome is using.
One possible cause is an open defect with HKEY_CURRENT_USER\Software\Policies\Google\Chrome\UserDataDir
But in my last case, it was some other unidentified cause.
Fortunately setting port number manually worked:
final String[] args = { "--remote-debugging-port=9222" };
options.addArguments(args);
WebDriver driver = new ChromeDriver(options);
As stated in this other answer:
This error message... implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.
Among the possible causes, I would like to mention the fact that, in case you are running an headless Chromium via Xvfb, you might need to export the DISPLAY variable: in my case, I had in place (as recommended) the --disable-dev-shm-usage and --no-sandbox options, everything was running fine, but in a new installation running the latest (at the time of writing) Ubuntu 18.04 this error started to occurr, and the only possible fix was to execute an export DISPLAY=":20" (having previously started Xvfb with Xvfb :20&).
You can get this error simply for passing bad arguments to Chrome. For example, if I pass "headless" as an arg to the C# ChromeDriver, it fires up great. If I make a mistake and use the wrong syntax, "--headless", I get the DevToolsActivePort file doesn't exist error.
I was stuck on this for a very long time and finally fixed it by adding this an additional option:
options.addArguments("--crash-dumps-dir=/tmp")
I know it's an old question and it already has a lot of answers. However, I ran into this issue, bumped into this thread and none of the proposed solutions helped. After spending a few days(!) on it I finally found a solution:
My problem was that I was using the selenium/standalone-chrome image on a MacBook with M1 chip. After switching to seleniarm/standalone-chromium everything finally started to work.
I had the same issue, but in my case chrome previously was installed in user temp folder, after that was reinstalled to Program files. So any of solution provided here was not help me. But if provide path to chrome.exe all works:
chromeOptions.setBinary("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");
I hope this helps someone =)
In my case it happened when I've tried to use my default user profile:
...
options.addArguments("user-data-dir=D:\\MyHomeDirectory\\Google\\Chrome\\User Data");
...
This triggered chrome to reuse processes already running in background, in such a way, that process started by chromedriver.exe was simply ended.
Resolution: kill all chrome.exe processes running in background.
update capabilities in conf.js as
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['todo-spec.js'],
capabilities: {
browserName: 'chrome',
chromeOptions: {
args: ['--disable-gpu', '--no-sandbox', '--disable-extensions', '--disable-dev-shm-usage']
}
},
};
Old question but a similar issue nearly drove me to insanity so sharing my solution. None of the other suggestions fixed my issue.
When I updated my Docker image Chrome installation from an old version to Chrome 86, I got this error. My setup was not identical but we were instantiating Chrome through a selenium webdriver.
The solution was to pass the options as goog:chromeOptions hash instead of chromeOptions hash. I truly don't know if this was a Selenium, Chrome, Chromedriver, or some other update, but maybe some poor soul will find solace in this answer in the future.
For Ubuntu 20 it did help me to use my systems chromium driver instead of the downloaded one:
# chromium which
/snap/bin/chromium
driver = webdriver.Chrome('/snap/bin/chromium.chromedriver',
options=chrome_options)
And for the downloaded webdriver looks like it needs the remote debug port --remote-debugging-port=9222 to be set, as in one of the answers (by Soheil Pourbafrani):
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--remote-debugging-port=9222")
driver = webdriver.Chrome('<path_to>/chromedriver', options=chrome_options)
Date 9/16/2021
Everything works fine running chrome with selenium locally with python inside the docker hosted ubuntu container. When attempting to run from Jenkins the error above is returned WebDriverException: unknown error: DevToolsActivePort
Environment:
-Ubuntu21.04 inside a docker container with RDP access.
-chromedriver for chrome version: 93
Solution:
Inside the python file that starts the browser I had to set the DISPLAY environment variable using the following lines:
import os
os.environ['DISPLAY'] = ':10.0'
#DISPLAY_VAR = os.environ.get('DISPLAY')
#print("DISPLAY_VAR:", DISPLAY_VAR)
In my case, I was trying to create a runnable jar on Windows OS with chrome browser and want to run the same on headless mode in unix box with CentOs on it. And I was pointing my binary to a driver that I have downloaded and packaged with my suite. For me, this issue continue to occur irrespective of adding the below:
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--no-sandbox");
System.setProperty("webdriver.chrome.args", "--disable-logging");
System.setProperty("webdriver.chrome.silentOutput", "true");
options.setBinary("/pointing/downloaded/driver/path/in/automationsuite");
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-gpu"); // applicable to windows os only
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("window-size=1024,768"); // Bypass OS security model
options.addArguments("--log-level=3"); // set log level
options.addArguments("--silent");//
options.setCapability("chrome.verbose", false); //disable logging
driver = new ChromeDriver(options);
Solution that I've tried and worked for me is, download the chrome and its tools on the host VM/Unix box, install and point the binary to this in the automation suite and bingo! It works :)
Download command:
wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
Install command:
sudo yum install -y ./google-chrome-stable_current_*.rpm
Update suite with below binary path of google-chrome:
options.setBinary("/opt/google/chrome/google-chrome");
And.. it works!
I also faced this issue while integrating with jenkins server, I was used the root user for jenkin job, the issue was fixed when I changed the user to other user. I am not sure why this error occurs for the root user.
Google Chrome Version 71.0
ChromeDriver Version 2.45
CentOS7 Version 1.153
I run selenium tests with Jenkins running on an Ubuntu 18 LTS linux. I had this error until I added the argument 'headless' like this (and some other arguments):
ChromeOptions options = new ChromeOptions();
options.addArguments("headless"); // headless -> no browser window. needed for jenkins
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox"); // Bypass OS security model
ChromeDriver driver = new ChromeDriver(options);
driver.get("www.google.com");
Had the same issue. I am running the selenium script on Google cloud VM.
options.addArguments("--headless");
The above line resolved my issue. I removed the other optional arguments. I think the rest lines of code mentioned in other answers did not have any effect on resolving the issue on the cloud VM.
in my case, when i changed the google-chrome and chromedriver version, the error was fixed :)
#google-chrome version
[root#localhost ~]# /usr/bin/google-chrome --version
Google Chrome 83.0.4103.106
#chromedriver version
[root#localhost ~]# /usr/local/bin/chromedriver -v
ChromeDriver 83.0.4103.14 (be04594a2b8411758b860104bc0a1033417178be-refs/branch-heads/4103#{#119})
ps: selenium verison was 3.9.1
No solution worked for my. But here is a workaround:
maxcounter=5
for counter in range(maxcounter):
try:
driver = webdriver.Chrome(chrome_options=options,
service_log_path=logfile,
service_args=["--verbose", "--log-path=%s" % logfile])
break
except WebDriverException as e:
print("RETRYING INITIALIZATION OF WEBDRIVER! Error: %s" % str(e))
time.sleep(10)
if counter==maxcounter-1:
raise WebDriverException("Maximum number of selenium-firefox-webdriver-retries exceeded.")
It seems there are many possible causes for this error. In our case, the error happened because we had the following two lines in code:
System.setProperty("webdriver.chrome.driver", chromeDriverPath);
chromeOptions.setBinary(chromeDriverPath);
It's solved by removing the second line.
I ran into same issue, i am using UBUNTU, PYTHON and OPERA browser. in my case the problem was originated because i had an outdated version of operadriver.
Solution:
1. Make sure you install latest opera browser version ( do not use opera beta or opera developer), for that go to the official opera site and download from there the latest opera_stable version.
Install latest opera driver (if you already have an opera driver install, you have to remove it first use sudo rm ...)
wget https://github.com/operasoftware/operachromiumdriver/releases/download/v.80.0.3987.100/operadriver_linux64.zip
unzip operadriver_linux64.zip
sudo mv operadriver /usr/bin/operadriver
sudo chown root:root /usr/bin/operadriver
sudo chmod +x /usr/bin/operadriver
in my case latest was 80.0.3987 as you can see
Additionally i also installed chromedriver (but since i did it before testing, i do not know of this is needed) in order to install chromedriver, follow the steps on previous step :v
Enjoy and thank me!
Sample selenium code
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Opera()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.quit()
I came across the same problem, in my case there are two different common user userA and userB in Linux system.
userA first run the selinium programe which start chrome browswer with ChromeDriver successfully, when it came to userB, the DevToolsActivePort file doesn't exist error occur.
I tried the --remote-debugging-port=9222 option, but it lead to a new exception:
selenium.common.exceptions.WebDriverException: Message: chrome not reachable
The I ran google-chome directory and see the following error:
mkdir /tmp/Crashpad/new: Permission denied (13)
The I search the problem and got this:
https://johncylee.github.io/2022/05/14/chrome-headless-%E6%A8%A1%E5%BC%8F%E4%B8%8B-devtoolsactiveport-file-doesn-t-exist-%E5%95%8F%E9%A1%8C/
chrome_options.add_argument(f"--crash-dumps-dir={os.path.expanduser('~/tmp/Crashpad')}")
Thanks to #johncylee.

How to set chrome driver path for centos

I am triying to run my testcase on centos but unable to set the path for driver can anyone help me to come out from this situation
I have one jar file which I want to run on sentos I have installed chrome driver on sentos server but. It is not taking driver path
If you're using the Java bindings for Selenium, you will have to specify the path to the ChromeDriver executable via the webdriver.chrome.driver system property. Depending on how you actually run your tests you can do this for example via the -D command line switch of the java executable:
java -jar mytests.jar -Dwebdriver.chrome.driver=/path/to/chromedriver

How does IEDriverServer.exe and Chromedriver.exe works?

I have following questions regarding seleniumn webdriver:
How does IEDriverServer.exe and Chromedriver. exe works. i.e. What happens when these exes are executed.
What is the significance of using these exes
These executables are used to run the webdrivers. These need to be specified in the System.setProperty. This is something that needs to be done for IE and Chrome but not for Firefox.
Running the .exe by themselves will probably do nothing.
Example Java Code for ChromeDriver:
System.setProperty("webdriver.chrome.driver","/.../chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(URL);

Selenium IDE - local (non-webhosted) file access for testing?

My Problem
When Selenium IDE is used to run a test, the "Base URL" is always accessed via http on some web server.
I need to know if (and how) its possible to get Selenium IDE to run a test on a locally stored file. When opening a file in Firefox, the path looks something like this in the Address Bar: file:///C:/Documents and Settings/username/My Documents/somehtml.html
However, Selenium gives a nasty error when I put this path in the Selenium IDE's Base URL field for my test (See bottom of my post).
What I tried
I run Windows XP and have tried switching the file path slashes to backslashes while keeping the protocol (file:///) slashes as is. I tried replacing spaces with %20 too.
I also considered whether my Firefox proxy settings might be causing an issue, but it isn't because if i open the file in Firefox it does so without issue.
The solution I'm working on is to avoid Selenium WebDriver at this phase. I know it is better on a technical but there are practical reasons why I can't use that at this point. Selenium IDE must be used for now.
Error
Error thrown when attempting to open local file:
[error] Unexpected Exception: name -> NS_ERROR_FAILURE, QueryInterface
-> function QueryInterface() { [native code] }, message -> Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)
[nsIDOMLocation.href], result -> 2147500037, filename ->
chrome://selenium-ide/content/selenium-core/scripts/selenium-browserbot.js,
lineNumber -> 686, columnNumber -> 0, location -> JS frame ::
chrome://selenium-ide/content/selenium-core/scripts/selenium-browserbot.js
:: BrowserBot.prototype.setOpenLocation :: line 686, inner -> null,
data -> null, initialize -> function initialize() { [native code] }
open about:config then change security.fileuri.strict_origin_policy to false. enjoy
One solution is to use the open command as the first line in your test, and set the local path as the target. This is fine for a handful of tests, but may not be sufficient for larger test suites.
command: open
target: file///c:/path/to/your/file.html
I had the same issue. Just solved it. Here is how:
Remove the base url.
Enter open or openWindow in command
Enter the file url in target e.g. file:///C:/temp/junk/SomeSiteAutomation/ABC.htm
Worked for me on FF 26 and Selenium 2.5
Open Selenium IDE - chrome extension
As soon as we open it will ask for project name and project url - just cancel it
Go to selenium IDE
In selenium IDE - in "command" text box select "open"
in "target" text box enter the path to sample html file as below
"file:///D:/index2.html"
Then this will show up in the command, target and value columns of the selenium ide.
Now just run the test. This will open up the local html file
I faced the same problem. I'm using Ubuntu and apache, but on Windows you can do the same.
move your index.html to /var/www/html (localhost points per default to this folder)
use http://127.0.0.1 as base_url in selenium ide
Right click on the Selenium IDE icon in the upper right of the browser window. Select "Manage Extensions" from the context menu. Toggle on "Allow access to file URLs" in the settings dialog.
This works in Chrome/Windows 10 and Version 3.17.0 of Selenium IDE.

Resources