jeffcook2150
jeffcook2150

Reputation: 4226

Extract pid of browser launched by Selenium WebDriver in Ruby

Does anyone know how to get the process id of the browser launched by Selenium WebDriver from the Ruby script that runs the WebDriver?

Upvotes: 4

Views: 2857

Answers (3)

zhisme
zhisme

Reputation: 2800

Both answers didn't work for me, 'cause this is a part of private api.
Checkout on github

require "selenium-webdriver" # gem 3.9.0

driver = Selenium::WebDriver.for :firefox
pid    = driver.instance_variable_get(:@service)
               .instance_variable_get(:@process)
               .instance_variable_get(:@pid)



NOTE:

For anyone who trying to access browser by pid, e.g. to execute kill -9 $pid command. It maybe wrong, cause I came across to a better solution.

In command args we can pass custom attrs. I use it like this

@buid   = SecureRandom.hex[0..15] # browser unique identifier
options = Selenium::WebDriver::Firefox::Options.new(
  args: [
    '-headless',
    "-buid=#{@buid}",
  ]
)

So then you can grep and kill both browser process and geckodriver. By exec

$ps aux | awk '/-buid=$generated_pid/ {print $2}' | xargs kill -9

Hope it helps!

Upvotes: 2

sougonde
sougonde

Reputation: 3618

The answer of Ben did not work for me, I had to adjust it to the following:

driver = Selenium::WebDriver.for :chrome

bridge = driver.instance_variable_get(:@bridge)
service = bridge.instance_variable_get(:@service)
process = service.instance_variable_get(:@process)
process.pid
# => 22656

Upvotes: 5

Ben Biddington
Ben Biddington

Reputation: 69

require "selenium-webdriver"

driver = Selenium::WebDriver.for :firefox

bridge = driver.instance_variable_get(:@bridge)
launcher = bridge.instance_variable_get(:@launcher)
binary = launcher.instance_variable_get(:@binary)
process = binary.instance_variable_get(:@process)
process.pid

Upvotes: 2

Related Questions