Esempio n. 1
0
    def __init__(self):
        global service, capabilities
        chromePath = readPath()
        if sys.platform == 'win32':
            service = services.Service('chromedriver.exe')
        elif sys.platform == 'darwin':
            service = services.Service('./chromedriver')
        capabilities = {'chrome.binary': chromePath}

        QtWidgets.QWidget.__init__(self)
        self.ui = uic.loadUi(getLoc('GUIS/itemConfig.ui'), self)
        self.setWindowIcon(QtGui.QIcon(getLoc('GUIS/icon.png')))
        self.label.setPixmap(QtGui.QPixmap(getLoc('GUIS/title.png')))
        self.strictItemSelect = True
        self.populateDropdowns()
        self.ui.category.currentIndexChanged.connect(self.updateFields)
        self.ui.add_item.clicked.connect(self.addItem)
        self.ui.delete_item.clicked.connect(self.removeItem)
        self.ui.start.clicked.connect(self.go)
        self.updateFields()
        self.menubar = self.menuBar()
        self.menubar.setStyleSheet(
            "QMenuBar::item::selected { background-color: rgb(200, 200, 200);}"
            "QMenuBar { background-color: rgb(226, 226, 226);}")
        optMenu = self.menubar.addMenu('Options')
        strictAct = QtWidgets.QAction('Strict item selection',
                                      self,
                                      checkable=True)
        strictAct.triggered.connect(self.strict)
        strictAct.setChecked(True)
        optMenu.addAction(strictAct)
Esempio n. 2
0
    def __init__(self):
        print("init")

        options = webdriver.ChromeOptions()
        options.add_argument("--headless")
        options.add_argument("--disable-gpu")


        service = chrome_service.Service("chromedriver")
        service.start()
        self.service = service
        self.capabilities = options.to_capabilities()
        # ---
        # self.driver = webdriver.Remote(
        #     command_executor='http://192.168.1.160:4444/wd/hub',
        #     desired_capabilities=options.to_capabilities()
        # )

        self.q = queue.Queue()
        self.exit_flag = False
        self.driver_mutex = threading.Lock()
        self.max_thread = max_printer
        self.threads_array = []

        for i in range(self.max_thread):
            thread = threading.Thread(target=self.c)
            thread.start()
            self.threads_array.append(thread)
Esempio n. 3
0
 def setup(self):
     svc = service.Service(self.driver_path)
     svc.start()
     options = webdriver.ChromeOptions()
     options.add_experimental_option(
         'prefs', {'download.default_directory': self.download_directory})
     self.driver = webdriver.Remote(svc.service_url)
Esempio n. 4
0
 def _StartServerIfNecessary(self):
   """Starts the ChromeDriver server, if not already started."""
   if self._chromedriver_server is None:
     exe = pyauto_paths.GetChromeDriverExe()
     assert exe, 'Cannot find chromedriver exe. Did you build it?'
     self._chromedriver_server = service.Service(exe)
     self._chromedriver_server.start()
def setup_driver():
    """
    seleniumを初期化する
    デバッグ時にはChromeの動作を目視確認するために、options.binary_location = '/usr/bin/chromium-browser'行をコメントアウトする。
    ヘッドレスモードを利用する場合は、options.add_argument行のコメントアウトを外す。
    """
    # WEB request header
    headers = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'
    }
    # Chromeを指定する
    chromedriver_location = '/usr/lib64/chromium-browser/chromedriver'
    chrome_service = fs.Service(executable_path=chromedriver_location)
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument(f'--user-agent={headers["User-Agent"]}')
    options.binary_location = '/usr/lib64/chromium-browser/headless_shell'
    # GUIによるデバッグ用。GUIでデバックする場合はこちらを選択する
    #options.binary_location = '/usr/bin/chromium-browser'
    driver = webdriver.Chrome(service=chrome_service, options=options)
    #driver.set_window_size('800', '600')
    mouse = webdriver.ActionChains(driver)
    return driver, mouse
Esempio n. 6
0
    def start(self, timeout=_DEFAULT_TIMEOUT):
        capabilities = {
            'chromeOptions': {
                'args': [
                    # This allows automated navigation to chrome:// URLs.
                    '--enable-gpu-benchmarking',
                    '--user-data-dir=%s' % self.user_data_dir_,
                ],
                'binary':
                self.chrome_,
            }
        }

        # Use a _ScopedStartStop helper so the service and driver clean themselves
        # up in case of any exceptions.
        _LOGGER.info('Starting chromedriver')
        with ScopedStartStop(service.Service(self.chromedriver_)) as \
            scoped_service:
            _LOGGER.info('Starting chrome')
            with ScopedStartStop(webdriver.Remote(scoped_service.service.service_url,
                                                  capabilities),
                                 start=lambda x: None, stop=lambda x: x.quit()) as \
                scoped_driver:
                self.pid_ = FindChromeProcessId(self.user_data_dir_, timeout)
                self.started_at_ = GetProcessCreationDate(self.pid_)
                _LOGGER.debug('Chrome launched.')
                self.driver_ = scoped_driver.release()
                self.service_ = scoped_service.release()
Esempio n. 7
0
def Download_Covid19_SCV(): #Chrome経由でfileを/tempに一度ダウンロードする
    driver_path = "Selenium/chromedriver.exe"
    chrome_service = service.Service(executable_path=driver_path)

    options = webdriver.ChromeOptions()
    options.add_argument('--headless')

    driver = webdriver.Chrome(service=chrome_service, options=options)
    driver.command_executor._commands["send_command"] = (
    "POST",
    '/session/$sessionId/chromium/send_command'
    )
    params = {
    'cmd': 'Page.setDownloadBehavior',
    'params': {
    'behavior': 'allow',
    'downloadPath': _my_folder+"\\tmp"
    }
    }
    driver.execute("send_command", params=params)
    driver.get("https://stopcovid19.metro.tokyo.lg.jp/data/130001_tokyo_covid19_details_testing_positive_cases.csv")
    time.sleep(1) # 秒
    covid19_data = pd.read_csv('tmp/130001_tokyo_covid19_details_testing_positive_cases.csv')
    driver.quit()
    return covid19_data
Esempio n. 8
0
 def start_headless(self):
     """Headless Chrome initiator."""
     print('Start headless browser')
     option_set = options.Options()
     option_set.add_arguments("test-type")
     option_set.add_arguments("start-maximized")
     option_set.add_arguments("--js-flags=--expose-gc")
     option_set.add_arguments("--enable-precise-memory-info")
     option_set.add_argument('headless')
     option_set.add_argument('disable-notifications')
     option_set.add_argument('disable-gpu')
     option_set.add_argument('disable-infobars')
     option_set.add_arguments("--disable-default-apps")
     option_set.add_arguments("test-type=browser")
     option_set.add_experimental_option(
         'prefs', {
             'credentials_enable_service': False,
             'profile': {
                 'password_manager_enabled': False
             }
         })
     option_set.binary_location = os.getenv(
         'CHROME_CANARY', '/Applications/Google Chrome Canary.app' +
         '/Contents/MacOS/Google Chrome Canary')
     webdriver_service = service.Service(
         os.getenv('CHROMEDRIVER', '/Applications/chromedriver'))
     webdriver_service.start()
     print('Service started; returning Remote webdriver')
     return webdriver.Remote(webdriver_service.service_url,
                             option_set.to_capabilities())
Esempio n. 9
0
def use_selenium(contest_id):
    url_contest_csv = f"https://www.draftkings.com/contest/exportfullstandingscsv/{contest_id}"
    bin_chromedriver = getenv("CHROMEDRIVER")
    if not getenv("CHROMEDRIVER"):
        exit("Could not find CHROMEDRIVER in env variable")

    logger.debug(f"Found chromedriver in env variable: {bin_chromedriver}")
    # start headless webdriver
    service = chrome_service.Service(bin_chromedriver)
    service.start()
    logger.debug("Starting driver with options")
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    # options.add_argument("--user-data-dir=/Users/Adam/Library/Application Support/Google/Chrome")
    # options.add_argument("--profile-directory=Default")
    driver = webdriver.Remote(service.service_url,
                              desired_capabilities=options.to_capabilities())

    logger.debug("Performing get on {}".format(url_contest_csv))
    driver.get(url_contest_csv)
    logger.debug(driver.current_url)
    logger.debug("Letting DK load ...")
    time.sleep(5)  # Let DK Load!
    logger.debug(driver.current_url)
    logger.debug("Letting DK load ...")
    time.sleep(5)  # Let DK Load!
    logger.debug(driver.current_url)
    logger.debug("Quitting driver")
    driver.quit()
Esempio n. 10
0
    def initialize(self):
        print("Initializing ChromeDriver Service")
        self.chrome_options = Options()
        self.chrome_options.add_argument("--headless")
        self.chrome_options.add_argument("--no-sandbox")
        chromedriver_path = None
        if sys.platform == "linux" or sys.platform == "linux2":
            from pixiegateway.webdriver import linux
            chromedriver_path = os.path.join(os.path.dirname(linux.__file__),
                                             "chromedriver")
        elif sys.platform == "darwin":
            from pixiegateway.webdriver import mac
            chromedriver_path = os.path.join(os.path.dirname(mac.__file__),
                                             "chromedriver")
        if chromedriver_path is None:
            raise Exception(
                "Unable to generate chart thumbnail. Invalid platform: {}".
                format(sys.platform))

        try:
            self.service = service.Service(chromedriver_path)
            self.service.start()
            self.chart_template = template.Loader(
                os.path.join(os.path.dirname(pixiegateway.__file__),
                             "template")).load("genThumbnail.html")

            print("ChromeDriver Service successfully initialized")
        except Exception as exc:
            self.exception = exc
def main():
    print("Starting!\n-------------------------------")
    options = webdriver.ChromeOptions()
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--enable-javascript')
    options.add_argument('--no-sandbox')
    #options.add_argument('--window-size=1920,1080')
    #options.add_argument('--start-maximized')
    #options.add_argument('--headless')

    my_service = service.Service(path_to_chromedriver)
    my_service.start()
    driver = webdriver.Remote(my_service.service_url,
                              desired_capabilities=options.to_capabilities())
    driver.get(twitter_url)

    input(
        "(1) Log in to Twitter\n(2)Make sure you're at home/Top Tweets\n(3)Press Enter/Return to continue..."
    )

    try:
        collect_timelines(driver, n_tweets=N_TWEETS, chronological=True)
    except TimeoutException as e:
        print("Timeout error...")
    except ConnectionRefusedError as e:
        print("Connection error...")
    except Exception as e:
        print("Unrecognized error: {}".format(str(e)))
    else:
        print("No errors...")
    finally:
        print("Done!")
        time.sleep(SCROLL_TIME)
        driver.quit()
Esempio n. 12
0
def demo_chrome():
    import time
    from selenium import webdriver
    import selenium.webdriver.chrome.service as service
    service = service.Service(
        '/Users/tv365/code/ant/src/config/chromedriver_mac243')
    service.start()
    # capabilities = {'chrome.binary': '/path/to/custom/chrome'}
    # driver = webdriver.Remote(service.service_url, capabilities)
    urls = [
        url.replace('\n', '')
        for url in open('/data/my_ant/play_urls').readlines()
    ]
    for i, url in enumerate(random.sample(urls, 10)):
        opts = ChromeOptions()
        opts.add_argument('--no-sandbox')
        opts.add_argument('--disable-dev-shm-usage')
        dcap = dict(DesiredCapabilities.CHROME)
        dcap["chrome.page.settings.loadImages"] = False
        opts.add_argument("--headless")
        driver = webdriver.Remote(service.service_url,
                                  options=opts,
                                  desired_capabilities=dcap)
        driver.get('http://www.google.com/xhtml')
        time.sleep(5)  # Let the user actually see something!
        driver.save_screenshot(str(i) + '.png')
        driver.quit()
    pass
Esempio n. 13
0
def browser(request):
    language = request.config.getoption("language")
    browser_name = request.config.getoption("browser_name")

    if browser_name == "chrome":
        print("\nstart chrome browser for test..")
        options = Options()
        options.add_experimental_option('prefs',
                                        {'intl.accept_languages': language})
        # "D:\\Apps\\Drivers\\chromedriver.exe" my path to chromedriver
        browser = webdriver.Chrome(options=options)

    elif browser_name == "opera":
        print("\nstart opera browser for test..")
        webdriver_service = service.Service(
            'D:\\Apps\\Drivers\\operadriver.exe')
        webdriver_service.start()
        options = webdriver.ChromeOptions()
        options.add_argument('--lang=' + language)
        browser = webdriver.Remote(webdriver_service.service_url,
                                   webdriver.DesiredCapabilities.OPERA,
                                   options=options)
    else:
        raise pytest.UsageError(
            "--browser_name should be chrome or opera, "
            "language should be in short form (en, uk, ru)")
    yield browser
    print("\nquit browser..")
    browser.quit()
Esempio n. 14
0
def main():
    global service, capabilities, password, items, reg, pDescr
    wsh = comclt.Dispatch("WScript.Shell")
    chromePath = readPath()

    service = service.Service(getLoc('chromedriver.exe'))
    capabilities = {'chrome.binary': chromePath}

    print("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-")
    print(
        "Thanks for using our bot. Please note this bot is experimental and in a very early development stage."
    )
    print(
        "This bot is simply a script. By deciding to use this bot you are responsible for any purchases. Not us."
    )
    print(
        "PLEASE ENTER THE CORRECT PATH TO YOUR CHROME.EXE IN THE 'chromepath.txt' FILE"
    )
    print("Read the README.md file carefully before use")
    print("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-")
    print(
        "\nFill out all the details, make sure you get all of them right. If you need help please open 'README.md' or check the reddit post."
    )

    reg = getRegion()

    if reg == 'EU':
        pDescr = EUpDescr
    elif reg == 'US':
        pDescr = USpDescr
    elif reg == 'ASIA':
        pDescr = ASIApDescr

    if not isPasswordExists():
        enc.paydetails = paydetails
        enc.initConf()
        getPDetails()
    else:
        inp = input('Do you want to use your stored details? [Y]es/[N]o: ')
        enc.update(paydetails)
        if inp.upper() == 'YES' or inp.upper() == 'Y':
            inp = input('Enter your password: '******'ascii')
            for x in paydetails:
                paydetails[x] = enc.readConf(x)
        else:
            getPDetails()

    if not confirmPayDetails():
        getPDetails()

    selectItemNum()

    items = []
    for x in range(itemNum):
        getItemDetails()

    openChrome()
    cart()
Esempio n. 15
0
 def start_opera(self, location):
     """Opera initiator."""
     webdriver_service = service.Service(location)
     webdriver_service.start()
     return webdriver.Remote(
         webdriver_service.service_url,
         DesiredCapabilities.OPERA.copy()
     )
Esempio n. 16
0
    def __init__(self, download_dir, save_dir):
        self.service = service.Service('chromedriver')
        self.browser = None
        self.is_started = False
        self.is_logged_in = False

        self.download_dir = download_dir
        self.save_dir = save_dir
Esempio n. 17
0
def newCDS():
    global service
    #https://duo.com/decipher/driving-headless-chrome-with-python    
    print('Starting chromedriverService at...', end='')
    service = service.Service('/usr/local/bin/chromedriver')
    service.start()
    CDS=service.service_url
    print( CDS )
    return CDS
Esempio n. 18
0
def _get_opera_driver():
    ''' Use OperaChromiumDriver for Opera testing.
    L{https://github.com/operasoftware/operachromiumdriver}
    L{https://github.com/operasoftware/operachromiumdriver/blob/master/docs/python-setup-step-by-step.md}
    L{https://github.com/operasoftware/operachromiumdriver/blob/master/docs/desktop.md}
    '''
    webdriver_service = service.Service(SELENIUM.get('OPERA_DRIVER', ""))
    webdriver_service.start()
    desired_caps = DesiredCapabilities.OPERA
    desired_caps['operaOptions'] = {'binary': SELENIUM.get('OPERA_BIN', "/usr/bin/opera")}
    return webdriver.Remote(webdriver_service.service_url, desired_caps)
Esempio n. 19
0
def start_server_and_driver():
    """
    Start the Selenium server and driver and return them as objects.
    """

    server = service.Service(PATH_TO_DRIVER)
    server.start()

    capabilities = {'chrome.binary': PATH_TO_BROWSER}
    driver = webdriver.Remote(server.service_url, capabilities)

    return server, driver
Esempio n. 20
0
    def __init__(self, headless=False, fullscreen=False, verbose=False):
        """Initialize a remotely controlled browser.

        If headless mode, the browser will not expect to be rendered onto a
        screen. This is handy for running in a Docker container, or in CI, for
        example.

        In fullscreen mode, the browser stretches itself to full screen on
        startup.

        """
        global VERBOSE
        VERBOSE = verbose

        if headless and fullscreen:
            raise Exception(
                'Headless and fullscreen modes are not compatible.')

        self.service = service.Service(PATH_TO_CHROMEDRIVER)
        self.service.start()

        # This is the desired resolution for screenshots. The actual window
        # size will be calculated with an offset for menus, etc.

        resolution = os.environ.get('BROWSER_RESOLUTION', '1280x800')
        resolution = resolution.split('x')
        resolution = (int(resolution[0]), int(resolution[1]))

        capabilities = dc.DesiredCapabilities.CHROME
        capabilities['chrome.binary'] = '/usr/bin/chromium-browser'
        capabilities['loggingPrefs'] = {'browser': 'ALL'}
        capabilities['chromeOptions'] = {
            'args': [
                '--user-agent="%s"' % USER_AGENT,
                '--window-size=%d,%d' % (resolution[0], resolution[1] + 72),
                '--disable-infobars',  # Hide "Chrome is being controlled..."
            ]
        }

        if headless:
            capabilities['chromeOptions']['useAutomationExtension'] = False
            capabilities['chromeOptions']['args'].extend([
                '--headless',
                '--disable-dev-shm-usage',
                '--no-sandbox',
            ])

        self.driver = webdriver.Remote(self.service.service_url, capabilities)
        self.driver.set_page_load_timeout(TIMEOUT)
        self.driver.set_script_timeout(TIMEOUT)

        if fullscreen:
            self.driver.fullscreen_window()
Esempio n. 21
0
    def __init__(self,
                 path_web_driver,
                 path_chrome,
                 status_display,
                 serv_url,
                 timer={
                     "short": 2,
                     "average": 4,
                     "long": 10
                 },
                 mode="CHROME"):
        """
        Класс создающий браузерное окно и выполняющий действия
        :param path_web_driver: путь до web драйвера
        :param path_chrome: путь до браузера chrome
        :param status_display: использовать ли скрытие дисплея с окном браузера
        :param serv_url: адрес сервера
        :param timer: три таймаута в секундах
        :param mode: определяет какой веб браузер будет запускаться

        """
        self.serv_url = serv_url
        self.path_web_driver = path_web_driver
        self.path_chrome = path_chrome
        self.web_driver = service.Service(path_web_driver)

        if mode == "CHROME":
            logger.info(" Start drive is Chrome mode...")
            #Блок Display определяет будет ли создан виртуальный display для теста
            self.display = {"Status": status_display}
            if self.display["Status"] == True:
                self.display["Display"] = Display(visible=0,
                                                  size=(1024, 768)).start()

            # Блок создает экземпляр driver
            self.web_driver.start()
            self.driver = webdriver.Remote(self.web_driver.service_url,
                                           {'chrome.binary': path_chrome})
            self.driver.get(self.serv_url)

        elif mode == "HTMLUNIT":
            logger.info(" Start drive is HTMLUNIT mode...")
            self.driver = webdriver.Remote(
                desired_capabilities=webdriver.DesiredCapabilities.HTMLUNIT)

        self.namepr = str

        self.time_1 = timer["short"]
        self.time_2 = timer["average"]
        self.time_3 = timer["long"]

        self.start_testTime = datetime
        self.end_testTime = datetime
class Opera():
    webdriver_service = service.Service(
        '/home/roman/PycharmProjects/webriver/operadriver/operadriver')
    webdriver_service.start()

    opera_profile = r'/home/roman/.config/opera'
    options = webdriver.ChromeOptions()
    options.add_argument('user-data-dir=' + opera_profile)
    # options._binary_location = '/usr/lib/x86_64-linux-gnu/opera'
    driver = webdriver.Remote(webdriver_service.service_url,
                              webdriver.DesiredCapabilities.OPERA,
                              options=options)
Esempio n. 23
0
    def start_server_and_driver(self):
        """
        Start the Selenium server and driver and return them as objects.
        =Args=
            self._path_to_driver: The path where the Selenium driver for your browser is saved.
            self._path_to_browser: The path where your browser application is saved.
        """

        self._server = service.Service(self._path_to_driver)
        self._server.start()

        capabilities = {'chrome.binary': self._path_to_browser}
        self._driver = webdriver.Remote(self._server.service_url, capabilities)
Esempio n. 24
0
 def create_opera_driver(self):
     """
     Setting Opera driver to be able to open URL.
     :return: WebDriver
     """
     logger.info("Preparing driver.")
     webdriver_service = service.Service(self.path)
     webdriver_service.start()
     driver = webdriver.Remote(webdriver_service.service_url,
                               self.capabilities)
     driver.maximize_window()
     logger.info("Driver is set.")
     return driver
Esempio n. 25
0
 def initiate_browser(self):
     path = self.settings['crawler']['selenium_driver_path']
     if self.settings['crawler']['selenium_browser'] == 'Firefox':
         fp = webdriver.FirefoxProfile()
         if self.settings['crawler']['browser_settings'][
                 'disable_javascript']:
             fp.set_preference("javascript.enabled", 'false')
         #~ fp.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')
         options = Options()
         if self.settings['crawler']['browser_settings']['headless']:
             options.set_headless(True)
         if path:
             brow = getattr(webdriver,
                            self.settings['crawler']['selenium_browser'])(
                                path, firefox_profile=fp, options=options)
             self.browser = brow
         else:
             brow = getattr(webdriver,
                            self.settings['crawler']['selenium_browser'])(
                                firefox_profile=fp, options=options)
             self.browser = brow
     elif self.settings['crawler']['selenium_browser'] == 'Chrome':
         serv = None
         if path:
             serv = service.Service(path)
         else:
             self.z_obj.pprint(
                 'Chrome requires a path to be set for Chromedriver', -1)
             exit()
         serv.start()
         if self.settings['crawler']['selenium_browser_path']:
             capabilities = {
                 'chrome.binary':
                 self.settings['crawler']['selenium_browser_path']
             }
             brow = webdriver.Remote(serv.service_url, capabilities)
             self.browser = brow
         else:
             brow = webdriver.Remote(serv.service_url, capabilities)
             self.browser = brow
     else:
         if path:
             brow = getattr(
                 webdriver,
                 self.settings['crawler']['selenium_browser'])(path)
             self.browser = brow
         else:
             brow = getattr(webdriver,
                            self.settings['crawler']['selenium_browser'])()
             self.browser = brow
     self.browser.set_page_load_timeout(self.settings['crawler']['timeout'])
Esempio n. 26
0
def start_server_and_driver(path_to_driver, path_to_browser):
    """
    Start the Selenium server and driver and return them as objects.
    =Parameters=
    path_to_driver: The path where the Selenium driver for your browser is saved.
    path_to_browser: The path where your browser application is saved.
    """

    server = service.Service(path_to_driver)
    server.start()

    capabilities = {'chrome.binary': path_to_browser}
    driver = webdriver.Remote(server.service_url, capabilities)

    return server, driver
Esempio n. 27
0
    def __init__(self):
        # Find the SCHWAB_USER and SCHWAB_PASSWORD through environment variable
        if 'SCHWAB_USER' not in os.environ:
            print("SCHWAB_USER must be defined in environment")
            sys.exit(1)
        if 'SCHWAB_PASSWORD' not in os.environ:
            print("SCHWAB_PASSWORD must be defined in environment")
            sys.exit(1)
        self.SCHWAB_USER = os.environ['SCHWAB_USER']
        self.SCHWAB_PASSWORD = os.environ['SCHWAB_PASSWORD']

        self.service = service.Service('chromedriver')
        self.browser = None
        self.is_started = False
        self.is_logged_in = False
Esempio n. 28
0
def init_driver_chrome():
    '''
    Initialize chrome browser. it needs a webdriver service
    '''
    import selenium.webdriver.chrome.service as service
    global service  # global variable because its needed in quit_driver()
    service = service.Service('chromedriver')
    service.start()
    print "service initialized for chrome browser"
    
    capabilities = {'chrome.loadAsync': 'true'}
    driver = webdriver.Remote(service.service_url, capabilities)
    driver.wait = WebDriverWait(driver, 5)
    driver.implicitly_wait(10)
    return driver
Esempio n. 29
0
    def __init__(self,
                 resolution="1024x768",
                 sequence="1",
                 screen="7",
                 temp_directory="/tmp/webbrowser"):
        self.resolution = resolution
        self.sequence = sequence
        self.screen = screen
        self.temp_directory = temp_directory

        self.xvfb_command = "Xvfb" + " :" + self.sequence + " -screen " + self.screen + " " + resolution + "x8"
        # print(self.xvfb_command)

        os.system("/usr/bin/pkill -f \"" + self.xvfb_command + "\"")
        os.system("nohup " + self.xvfb_command + " >/dev/null 2>&1 &")
        try:
            os.makedirs(self.temp_directory)
        except:
            pass

        self.service = ChromeDriverService.Service(
            executable_path=self.chrome_driver,
            service_args=[
                "--log-path=" + self.temp_directory + "/log.txt", "--verbose"
            ],
            env={"DISPLAY": ":" + self.sequence + "." + self.screen})
        self.service.start()

        #                    "--ash-host-window-bounds=" + resolution,
        self.capabilities = {
            'chrome.binary': self.chrome_browser,
            'chromeOptions': {
                "args": [
                    "--no-sandbox", "--kiosk",
                    "--user-data-dir=" + self.temp_directory
                ]
            }
        }
        try:
            self.driver = webdriver.Remote(self.service.service_url,
                                           self.capabilities)
        except Exception as e:
            print("Unable to initialize webdriver.Remote")
            print(e)

        r = resolution.split("x")
        self.driver.set_window_size(int(r[0]), int(r[1]))
Esempio n. 30
0
    def _setup(self):
        os_name = platform.system()
        # setup when run on Windows
        if (os_name == 'Windows'):
            return webdriver.Chrome(food.WINDOWS_CHROME_DRIVER)

        # setup when run on Linux
        a_service = service.Service(food.LINUX_CHROME_DRIVER)
        a_service.start()
        capabilities = {
            'chrome.binary': food.LINUX_CHROME_STABLE,
            "chromeOptions": {
                "args": ['--no-sandbox']
            }
        }

        return webdriver.Remote(a_service.service_url, capabilities)