Get PID of Browser launched by selenium

前端 未结 9 1571
闹比i
闹比i 2020-11-30 07:15

I would like to get the PID of the browser launched by selenium. Is there any way to get it done?

9条回答
  •  一个人的身影
    2020-11-30 07:52

    for the guys comming here to find a solution, here it is, hope it will help you out.

    protected Integer getFirefoxPid(FirefoxBinary binary){
        try {
            final Field fieldCmdProcess = FirefoxBinary.class.getDeclaredField("process");
            fieldCmdProcess.setAccessible(true);
            final Object ObjCmdProcess = fieldCmdProcess.get(binary);
    
            final Field fieldInnerProcess = ObjCmdProcess.getClass().getDeclaredField("process");
            fieldInnerProcess.setAccessible(true);
            final Object objInnerProcess = fieldInnerProcess.get(ObjCmdProcess);
    
            final Field fieldWatchDog = objInnerProcess.getClass().getDeclaredField("executeWatchdog");
            fieldWatchDog.setAccessible(true);
            final Object objWatchDog = fieldWatchDog.get(objInnerProcess);
    
            final Field fieldReelProcess = objWatchDog.getClass().getDeclaredField("process");
            fieldReelProcess.setAccessible(true);
            final Process process = (Process) fieldReelProcess.get(objWatchDog);
    
            final Integer pid;
    
            if (Platform.getCurrent().is(WINDOWS)) {
                final Field f = process.getClass().getDeclaredField("handle");
                f.setAccessible(true);
                long hndl = f.getLong(process);
    
                final Kernel32 kernel = Kernel32.INSTANCE;
                final WinNT.HANDLE handle = new WinNT.HANDLE();
                handle.setPointer(Pointer.createConstant(hndl));
                pid = kernel.GetProcessId(handle);
    
            } else {
                final Field f = process.getClass().getDeclaredField("pid");
                f.setAccessible(true);
                pid = (Integer) f.get(process);
            }
            logger.info("firefox process id : " + pid + " on plateform : " + Platform.getCurrent());
            return pid;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Cannot get firefox process id, exception is : {}", e);
        }
        return null;
    }
    

提交回复
热议问题