Programing

Selenium Webdriver가 백그라운드에서 자동으로 브라우저 창을 열 수 있습니까?

lottogame 2020. 6. 25. 08:02
반응형

Selenium Webdriver가 백그라운드에서 자동으로 브라우저 창을 열 수 있습니까?


나는 많은 테스트를 실행하는 셀레늄 테스트 스위트를 가지고 있으며 각각의 새로운 테스트에서 열려있는 다른 창 위에 브라우저 창을 엽니 다. 로컬 환경에서 작업하는 동안 매우 부끄럽습니다. 백그라운드에서 창을 열도록 셀레늄 또는 OS (MAC)에 지시하는 방법이 있습니까?


몇 가지 방법이 있지만 간단한 "구성 값 설정"은 아닙니다. 모든 사람의 요구 사항에 맞지 않는 헤드리스 브라우저에 투자하지 않는 한 약간의 해킹입니다.

Firefox 창을 숨기는 방법 (Selenium WebDriver)?

Selenium RC에서 브라우저를 숨길 수 있습니까?

``추정 적으로 '', 일부 매개 변수를 Chrome에 전달할 수 있습니다. --no-startup-window

일부 브라우저, 특히 IE의 경우 초점이 맞지 않으면 테스트가 손상됩니다.

AutoIT로 조금 해킹하여 창이 열리면 창을 숨길 수도 있습니다.


Python과 함께 Selenium 웹 드라이버를 사용하는 경우 Xvfb 및 Xephyr 용 Python 래퍼 인 PyVirtualDisplay를 사용할 수 있습니다.

PyVirtualDisplay는 Xvfb를 종속성으로 필요로합니다. 우분투에서 먼저 Xvfb를 설치하십시오 :

sudo apt-get install xvfb

그런 다음 Pypi에서 PyVirtualDisplay를 설치하십시오.

pip install pyvirtualdisplay

PyVirtualDisplay를 사용하여 헤드리스 모드에서 Python의 샘플 Selenium 스크립트 :

#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

# now Firefox will run in a virtual display. 
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()

display.stop()

편집 초기 답변은 2014 년에 게시되었으며 이제 우리는 2018 년을 맞이했습니다. 다른 모든 것과 마찬가지로 브라우저도 발전했습니다. Chrome에는 이제 완전히 헤드리스 버전이 있으므로 타사 라이브러리를 사용하여 UI 창을 숨길 필요가 없습니다. 샘플 코드는 다음과 같습니다.

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

CHROME_PATH = '/usr/bin/google-chrome'
CHROMEDRIVER_PATH = '/usr/bin/chromedriver'
WINDOW_SIZE = "1920,1080"

chrome_options = Options()  
chrome_options.add_argument("--headless")  
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.binary_location = CHROME_PATH

driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,
                          chrome_options=chrome_options
                         )  
driver.get("https://www.google.com")
driver.get_screenshot_as_file("capture.png")
driver.close()

Chrome 57에는 --headless 플래그를 전달하여 창이 보이지 않게하는 옵션이 있습니다.

마지막 플래그가 창을 시작하지 않으므로이 플래그는 --no-startup-window와 다릅니다. 이 페이지에서 말하는 것처럼 백그라운드 앱을 호스팅하는 데 사용됩니다 .

플래그를 Selenium 웹 드라이버 (ChromeDriver)에 전달하는 Java 코드 :

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
ChromeDriver chromeDriver = new ChromeDriver(options);

Chrome 57부터 헤드리스 논쟁이 있습니다.

var options = new ChromeOptions();
options.AddArguments("headless");
using (IWebDriver driver = new ChromeDriver(options))
{
    // the rest of your test
}

Chrome의 헤드리스 모드는 UI 버전보다 30.97 % 더 우수합니다. 다른 헤드리스 드라이버 인 PhantomJS는 Chrome의 헤드리스 모드보다 34.92 % 더 우수합니다.

팬텀 JSDriver

using (IWebDriver driver = new PhantomJSDriver())
{
     // the rest of your test
}

Mozilla Firefox의 헤드리스 모드는 UI 버전보다 3.68 % 더 좋습니다. Chrome의 헤드리스 모드가 UI보다 30 % 더 나은 시간을 달성하기 때문에 실망합니다. 다른 헤드리스 드라이버 인 PhantomJS는 Chrome의 헤드리스 모드보다 34.92 % 더 우수합니다. 놀랍게도 Edge 브라우저는 모든 것을 능가합니다.

var options = new FirefoxOptions();
options.AddArguments("--headless");
{
    // the rest of your test
}

Firefox 57 이상에서 사용할 수 있습니다

Mozilla Firefox의 헤드리스 모드는 UI 버전보다 3.68 % 더 좋습니다. Chrome의 헤드리스 모드가 UI보다 30 % 더 나은 시간을 달성하기 때문에 실망합니다. 다른 헤드리스 드라이버 인 PhantomJS는 Chrome의 헤드리스 모드보다 34.92 % 더 우수합니다. 놀랍게도 Edge 브라우저는 모든 것을 능가합니다.

Note: PhantomJS is not maintained any more!


For running without any browser, you can run it in headless mode.

I show you one example in Python that is working for me right now

from selenium import webdriver


options = webdriver.ChromeOptions()
options.add_argument("headless")
self.driver = webdriver.Chrome(executable_path='/Users/${userName}/Drivers/chromedriver', chrome_options=options)

I also add you a bit more of info about this in the official Google website https://developers.google.com/web/updates/2017/04/headless-chrome


I suggest using Phantom Js for more info you need to visit Phantom Official Website

As far as i know PhantomJS work only with Firefox ..

after downloading PhantomJs.exe you need to import to your project as you can see in the picture below Phantomjs is inside common>>Library>>phantomjs.exe enter image description here

Now all You have to inside your Selenium code is to change the line

browser = webdriver.Firefox()

To something like

import os
path2phantom = os.getcwd() + "\common\Library\phantomjs.exe"
browser = webdriver.PhantomJS(path2phantom)

The path to phantomjs may be different... change as you like :)

That's it, it worked for me. and definitely he will work for you to, Cheers


On windows you can use win32gui:

import win32gui
import win32con
import subprocess

class HideFox:
    def __init__(self, exe='firefox.exe'):
        self.exe = exe
        self.get_hwnd()


    def get_hwnd(self):
      win_name = get_win_name(self.exe)
      self.hwnd = win32gui.FindWindow(0,win_name)


    def hide(self):
        win32gui.ShowWindow(self.hwnd, win32con.SW_MINIMIZE)
        win32gui.ShowWindow(self.hwnd, win32con.SW_HIDE)

    def show(self):
        win32gui.ShowWindow(self.hwnd, win32con.SW_SHOW)
        win32gui.ShowWindow(self.hwnd, win32con.SW_MAXIMIZE)

def get_win_name(exe):
    '''simple function that gets the window name of the process with the given name'''
    info = subprocess.STARTUPINFO()
    info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    raw=subprocess.check_output('tasklist /v /fo csv', startupinfo=info).split('\n')[1:-1]
    for proc in raw:
        try:
            proc=eval('['+proc+']')
            if proc[0]==exe:
                return proc[8]             
        except:
            pass
    raise ValueError('Could not find a process with name '+exe)

Example:

hider=HideFox('firefox.exe')  #can be anything, eq: phantomjs.exe, notepad.exe ...
#To hide the window
hider.hide()
#To show again
hider.show()

However there is one problem with this solution - using send_keys method makes the window show up. You can deal with it by using javascript which does not show window:

def send_keys_without_opening_window(id_of_the_element, keys)
    YourWebdriver.execute_script("document.getElementById('" +id_of_the_element+"').value = '"+keys+"';")

It may be in options. Here is the identical java code.

        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setHeadless(true);
        WebDriver driver = new ChromeDriver(chromeOptions);

On *nix, you can also run a headless X-server like Xvfb and point the DISPLAY variable to it:

Fake X server for testing?


Here is a .net solution that worked for me:

Download PhantomJs here http://phantomjs.org/download.html

Copy the .exe from the bin folder in the download and paste in the bin debug/release folder of your Visual Studio project.

Add this using

using OpenQA.Selenium.PhantomJS;

In your code open the driver like this:

PhantomJSDriver driver = new PhantomJSDriver();
using (driver)
{
   driver.Navigate().GoToUrl("http://testing-ground.scraping.pro/login");
   //your code here 
}

If you are using Ubuntu (Gnome), one simple workaround is to install Gnome extension auto-move-window: https://extensions.gnome.org/extension/16/auto-move-windows/

Then set the browser (eg. Chrome) to another workspace (eg. Workspace 2). The browser will silently run in other workspace and not bother you anymore. You can still use Chrome in your workspace without any interruption.


hi i had the same problem with my chromedriver using python and options.add_argument("headless") did not work for me but then i realized how to fix it so i bring it in code below

opt=webdriver.ChromeOptions()
opt.arguments.append("headless")

i hope it works for you.


This is a simple NodeJS solution that works in the new version 4.x (maybe also 3.x) of Selenium.

Chrome:

const { Builder } = require('selenium-webdriver')
const chrome = require('selenium-webdriver/chrome');

let driver = await new Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless()).build()

await driver.get('https://example.com')

Firefox:

const { Builder } = require('selenium-webdriver')
const firefox = require('selenium-webdriver/firefox');

let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(new firefox.Options().headless()).build()

await driver.get('https://example.com')

The whole thing just runs in the background. Exactly what we want.

참고URL : https://stackoverflow.com/questions/16180428/can-selenium-webdriver-open-browser-windows-silently-in-background

반응형