Python selenium.webdriver.chrome.options.Options() Examples

The following are 27 code examples for showing how to use selenium.webdriver.chrome.options.Options(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

 

 
Example 1
Project: bawangcan   Author: mascure   File: bawangcan.py View Source Project 6 votes vote downvote up
def main():
    print 'hello'

    print sys.argv
    print len(sys.argv)
    dper= sys.argv[1]
    print "your dper is:"+dper

    opts = Options()
    opts.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.86 Safari/537.36")
    driver = webdriver.Chrome(chrome_options=opts)
    driver.maximize_window()

    driver.get("http://s.dianping.com/event/119124")
    driver.add_cookie({'name':'dper', 'value':dper,'path':'/'})
    category_urls=[]
    category_urls.append("http://s.dianping.com/event/shanghai/c1")
    category_urls.append("http://s.dianping.com/event/shanghai/c6")
    for url in category_urls:
        process_category(url, driver)
    driver.quit()
Example 2
Project: baselayer   Author: cesium-ml   File: test_util.py View Source Project 6 votes vote downvote up
def driver(request):
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    chrome_options = Options()

    chromium = distutils.spawn.find_executable('chromium-browser')

    if chromium:
        chrome_options.binary_location = chromium

    chrome_options.add_argument('--browser.download.folderList=2')
    chrome_options.add_argument(
        '--browser.helperApps.neverAsk.saveToDisk=application/octet-stream')
    prefs = {'download.default_directory': '/tmp'}
    chrome_options.add_experimental_option('prefs', prefs)

    driver = MyCustomWebDriver(chrome_options=chrome_options)
    driver.set_window_size(1400, 1080)
    login(driver)

    yield driver

    driver.close()

 

 
Example 3
Project: Flask-MVC-Template   Author: CharlyJazz   File: test_front_end.py View Source Project 6 votes vote downvote up
def setUp(self):
        from selenium.webdriver.chrome.options import Options
        chrome_options = Options()
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--disable-setuid-sandbox")

        """Setup the test driver and create test users"""
        self.driver = webdriver.Chrome(chrome_options=chrome_options)
        self.driver.get(self.get_server_url())

        email_admin = test_admin_email

        db.session.commit()
        db.drop_all()
        db.create_all()

        user_datastore.create_user(email=test_admin_email, username=test_admin_username, password=test_admin_password)
        user_datastore.create_user(email=test_user_final_email, username=test_user_final_username, password=test_user_final_password)
        user_datastore.find_or_create_role(name='admin', description='Administrator')
        user_datastore.find_or_create_role(name='end-user', description='End user')
        user_datastore.add_role_to_user(email_admin, 'admin')
        db.session.commit()

 

 
Example 4
Project: xfinity-usage   Author: jantman   File: xfinity_usage.py View Source Project 5 votes vote downvote up
def get_browser(self):
        """get a webdriver browser instance """
        if self.browser_name == 'firefox':
            logger.debug("getting Firefox browser (local)")
            if 'DISPLAY' not in os.environ:
                logger.debug("exporting DISPLAY=:0")
                os.environ['DISPLAY'] = ":0"
            browser = webdriver.Firefox()
        elif self.browser_name == 'chrome':
            logger.debug("getting Chrome browser (local)")
            browser = webdriver.Chrome()
        elif self.browser_name == 'chrome-headless':
            logger.debug('getting Chrome browser (local) with --headless')
            chrome_options = Options()
            chrome_options.add_argument("--headless")
            browser = webdriver.Chrome(chrome_options=chrome_options)
        elif self.browser_name == 'phantomjs':
            logger.debug("getting PhantomJS browser (local)")
            dcap = dict(DesiredCapabilities.PHANTOMJS)
            dcap["phantomjs.page.settings.userAgent"] = self.user_agent
            args = [
                '--ssl-protocol=any',
                '--ignore-ssl-errors=true',
                '--web-security=false'
            ]
            browser = webdriver.PhantomJS(
                desired_capabilities=dcap, service_args=args
            )
        else:
            raise SystemExit(
                "ERROR: browser type must be one of 'firefox', 'chrome', "
                "'phantomjs', or 'chrome-headless' not '{b}'".format(
                    b=self.browser_name
                )
            )
        browser.set_window_size(1024, 768)
        logger.debug("returning browser")
        return browser 
Example 5
Project: open-source-feeds   Author: mhfowler   File: fbscrape.py View Source Project 5 votes vote downvote up
def initialize_driver(self, driver=None):
        if self.command_executor:
            chrome_options = Options()
            chrome_options.add_argument("--disable-notifications")
            if self.proxy:
                chrome_options.add_argument('--proxy-server=%s' % self.proxy)
            self.driver = webdriver.Remote(
                command_executor=self.command_executor,
                desired_capabilities=chrome_options.to_capabilities()
            )
        else:
            if self.which_driver == 'phantomjs':
                dcap = dict(DesiredCapabilities.PHANTOMJS)
                dcap["phantomjs.page.settings.userAgent"] = (
                    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 "
                    "(KHTML, like Gecko) Chrome/15.0.87"
                )
                driver = webdriver.PhantomJS(desired_capabilities=dcap)
                driver.set_window_size(1400, 1000)
                self.driver = driver
            elif self.which_driver == 'chrome':
                chrome_options = Options()
                chrome_options.add_argument("--disable-notifications")
                if self.proxy:
                    chrome_options.add_argument('--proxy-server=%s' % self.proxy)
                self.driver = webdriver.Chrome(chrome_options=chrome_options)
            # otherwise use the driver passed in
            else:
                self.driver = driver
        # set page load timeout
        self.driver.set_page_load_timeout(time_to_wait=240)
Example 6
Project: bitmask-dev   Author: leapcode   File: environment.py View Source Project 5 votes vote downvote up
def _setup_webdriver(context):
    chrome_options = Options()
    # argument to switch off suid sandBox and no sandBox in Chrome
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-setuid-sandbox")

    context.browser = webdriver.Chrome(chrome_options=chrome_options)
    context.browser.set_window_size(1280, 1024)
    context.browser.implicitly_wait(DEFAULT_IMPLICIT_WAIT_TIMEOUT_IN_S)
    context.browser.set_page_load_timeout(60)
Example 7
Project: callisto-core   Author: project-callisto   File: test_frontend.py View Source Project 5 votes vote downvote up
def setup_browser(cls):
        chrome_options = Options()
        # deactivate with `HEADED=TRUE pytest...`
        if headless_mode():
            chrome_options.add_argument("--headless")
            chrome_options.add_argument('--no-sandbox')
            chrome_options.add_argument("--disable-gpu")
        cls.browser = webdriver.Chrome(
            chrome_options=chrome_options,
        )
Example 8
Project: TestRewrite   Author: osqa-interns   File: helper.py View Source Project 5 votes vote downvote up
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()
        )
Example 9
Project: beryl   Author: DanielJDufour   File: test.py View Source Project 5 votes vote downvote up
def setUpModule():
    global driver

    print "starting setUpModule"
    call( [ "killall", "-9", "chrome" ] )
    options = Options()
    options.add_extension(path_to_chrome_extension)
    options.add_argument("--start-maximized")
    driver = webdriver.Chrome(executable_path=path_to_chrome_driver, chrome_options=options)
    print "finished setUpModule"
Example 10
Project: football_data   Author: andrebrener   File: game_data.py View Source Project 5 votes vote downvote up
def get_games_id(comp):

    dates = [d for d in date_range(START_DATE, END_DATE)]
    games_id = []

    chrome_options = Options()
    chrome_options.add_argument('--dns-prefetch-disable')
    driver = Chrome(chrome_options=chrome_options)

    for day in dates:
        driver.get(
            'http://www.espn.com.ar/futbol/resultados/_/liga/{}/fecha/{}'.
            format(comp, day))

        game_link_driver = driver.find_elements_by_class_name(
            'mobileScoreboardLink  ')

        print(game_link_driver)
        for game_driver in game_link_driver:
            game_id = game_driver.get_attribute('href')[46:53]
            games_id.append((game_id, day))

        driver.quit

    # print(games_id)
    return games_id 
Example 11
Project: biweeklybudget   Author: jantman   File: make_screenshots.py View Source Project 5 votes vote downvote up
def _get_browser(self):
        copt = Options()
        copt.add_argument('--headless')
        b = webdriver.Chrome(chrome_options=copt)
        b.set_window_size(1920, 1080)
        b.implicitly_wait(2)
        return b 
Example 12
Project: django-radar   Author: chairco   File: crawler_selenium.py View Source Project 5 votes vote downvote up
def _driver(self):
        if self.virtual:
            self.display = Display(visible=0, size=(1024, 786))
            self.display.start()
        
        service_args = [
        '--webdriver-loglevel=ERROR'  # only record ERROR message
        '--proxy=127.0.0.1:3128',
        ]
        
        # setting Chrome option
        os.environ['webdriver.chrome.driver'] = self.driver_path
        prefs = {'download.default_directory': self.download_path_temp}
        proxy = '127.0.0.1:3128'
        
        chrome_options = Options()
        chrome_options.add_experimental_option('prefs', prefs)
        chrome_options.add_argument('--proxy-server=http://%s' % proxy)

        driver = webdriver.Chrome(
            executable_path=self.driver_path, # ?? dirver ??
            service_log_path=self.logs_path, # ?? log ????
            chrome_options=chrome_options, # ????????
            #service_args=service_args,
        )
        return driver 
Example 13
Project: reahl   Author: reahl   File: fixtures.py View Source Project 5 votes vote downvote up
def new_chrome_options(self):
        from selenium.webdriver.chrome.options import Options
        options = Options()
        options.add_argument('--disable-preconnect')
        options.add_argument('--dns-prefetch-disable')
        options.add_argument('--start-maximized')
        options.add_argument('--no-sandbox')  # Needed to be able to run a user-installed version of chromium on travis
        options.binary_location = Executable('chromium-browser').executable_file  # To run a custom-installed chromium as picked up by the PATH
        #--enable-http-pipelining
        #--learning
        #--single-process
        return options 
Example 14
Project: test-automation   Author: openstax   File: helper.py View Source Project 5 votes vote downvote up
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()
        )
Example 15
Project: test-automation   Author: openstax   File: test_02_AboutUs.py View Source Project 5 votes vote downvote up
def setUp(self):
        """Pretest settings."""
        # Remove the info bars and password save alert from Chrome
        option_set = options.Options()
        option_set.add_argument("disable-infobars")
        option_set.add_experimental_option(
            'prefs', {
                'credentials_enable_service': False,
                'profile': {
                    'password_manager_enabled': False
                }
            }
        )
        self.driver = webdriver.Chrome(chrome_options=option_set)

        # Retrieve the defined server or default to the QA instance
        self.driver.get(getenv('OSWEBSITE', 'https://oscms-qa.openstax.org'))
        self.wait = WebDriverWait(self.driver, 15)
        link = self.wait.until(
            expect.presence_of_element_located(
                (By.CSS_SELECTOR, '[href="/about"]')
            )
        )
        self.driver.execute_script(
            'return arguments[0].scrollIntoView();',
            link
        )
        sleep(2.5)
        link.click()
Example 16
Project: django-wizard-builder   Author: project-callisto   File: base.py View Source Project 5 votes vote downvote up
def setUpClass(cls):
        super(FunctionalTest, cls).setUpClass()
        chrome_options = Options()
        chrome_options.add_argument("--headless")
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument("--disable-gpu")
        cls.browser = webdriver.Chrome(
            chrome_options=chrome_options,
        )
Example 17
Project: winnaker   Author: target   File: models.py View Source Project 5 votes vote downvote up
def __init__(self):
        chrome_options = Options()
        chrome_options.add_argument("--disable-extensions")
        chrome_options.add_argument("--no-sandbox")
        self.driver = webdriver.Chrome(chrome_options=chrome_options)
        # self.driver = webdriver.Firefox()
        time.sleep(1)
        self.driver.get(cfg_spinnaker_url)
        self.wait = WebDriverWait(self.driver, 10)
        if not os.path.exists(cfg_output_files_path):
            os.makedirs(cfg_output_files_path)
Example 18
Project: adidas-multi-session   Author: yzyio   File: bot.py View Source Project 5 votes vote downvote up
def transfer_session(browser):
    driver = browser['browser']
    logging.info("[New Thread] Transferring session {}".format(driver.session_id))

    # Save cookies
    write_cookies_to_file(driver.get_cookies())

    url = driver.current_url

    chrome_options = Options()
    chrome_options.add_argument("user-agent={}".format(browser['user_agent']))
    chrome_options.add_argument("--proxy-server=http://{}".format(browser['proxy'][0]))
    chrome = webdriver.Chrome(executable_path=find_path('chromedriver'), chrome_options=chrome_options)

    # Open URL and wait for proxy login
    chrome.get(url)
    logging.info("[CHROME/PROXY] Login with {}".format(browser['proxy'][1]))

    chrome.implicitly_wait(10)
    element = WebDriverWait(chrome, 1000).until(EC.presence_of_element_located((By.TAG_NAME, "div")))

    # Transfer Cookies
    chrome.delete_all_cookies()
    for cookie in driver.get_cookies():
        chrome.add_cookie(cookie)

    chrome.refresh()
    time.sleep(10000)
Example 19
Project: badger-claw   Author: cowlicks   File: crawler.py View Source Project 5 votes vote downvote up
def start_driver():
    opts = Options()
    opts.add_extension(get_extension_path())
    opts.add_experimental_option("prefs", {"profile.block_third_party_cookies": False})
    opts.add_argument('--dns-prefetch-disable')
    return webdriver.Chrome(config.CHROMEDRIVER_PATH, chrome_options=opts)
Example 20
Project: scraping-hands-on   Author: orangain   File: 08_note.py View Source Project 5 votes vote downvote up
def main():
    """
    ???????
    """

    options = Options()
    # Chrome????Stable?????--headless?????????????????
    options.binary_location = '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary'
    # ???????????????????????????????????????
    options.add_argument('--headless')
    # Chrome?WebDriver????????????
    driver = webdriver.Chrome(chrome_options=options)

    driver.get('https://note.mu/')  # note???????????
    assert 'note' in driver.title  # ?????'note'???????????????

    # 10???????????WebDriverWait??????????????
    wait = WebDriverWait(driver, 10)
    # ???class="p-post--basic"??????????
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.p-post--basic')))

    posts = scrape_posts(driver)  # ?????????????????

    # ??????????????
    for post in posts:
        print(post['title'])
        print(post['url'])
Example 21
Project: ScatterFly   Author: nikshepsvn   File: make_noise.py View Source Project 4 votes vote downvote up
def start_drivers():
    print("\n\nAttempting to initialize drivers....")
    #if user is using RPi, make sure that the virtual display has been setup or else exit

    if 'raspberrypi' in platform.uname() or 'armv7l' == platform.machine():
        #if user is running on raspberrypi and hasnt set up xvfb properly print instruction on how to set up and exit code
        if not os.getenv('DISPLAY'):
            print("\nPlease make sure that your virtual display is setup correctly and try again!")
            print("\nMake sure you have executed the following commands: ")
            print("\n1. xvfb :99 -ac &")
            print("\n2. export DISPLAY=:99")
            print("\nNow exiting Program...")
            sys.exit(1)

        #adding options to firefox driver
        from selenium.webdriver.firefox.options import Options
        firefox_options = Options()
        firefox_options.add_argument("--headless") #starting firefox in headless mode
        firefox_options.add_argument("--mute-audio") #starting firefox without audio
        firefox_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36")
        #initializing driver with options
        p = currentpath + '/drivers/geckodriver_arm7'
        return webdriver.Firefox(executable_path = p, firefox_options = firefox_options)
        print("\nDrivers for RaspberryPi has been initialized succesfully!")

    else:
        #enters here if device is not a RPi
        #creating a chrome options object that is later going to be attached with the driver!
        from selenium.webdriver.chrome.options import Options
        chrome_options = Options()
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--mute-audio")
        chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36")
        #choosing and initializing driver based on OS

        if 'Linux' in (sysplatform):
            print("\nDrivers for Linux has been initialized succesfully!")
            return webdriver.Chrome(currentpath +'/drivers/chromedriver_linux',chrome_options = chrome_options)

        elif 'Windows' in (sysplatform):
            print("\nDrivers for Windows has been initialized succesfully!")
            return webdriver.Chrome(currentpath +'/drivers/chromedriver.exe',chrome_options = chrome_options)

        elif 'Darwin' in (sysplatform):
            print("\nDrivers for OSX has been initialized succesfully!")
            return webdriver.Chrome(currentpath +'/drivers/chromedriver_mac',chrome_options = chrome_options)


#function that asks user permission to access previous data 
Example 22
Project: TwitPy   Author: timgrossmann   File: twitpy.py View Source Project 4 votes vote downvote up
def __init__(self, username=None, password=None, nogui=False):
    if nogui:
      self.display = Display(visible=0, size=(800, 600))
      self.display.start()

    chrome_options = Options()
    chrome_options.add_argument('--dns-prefetch-disable')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--lang=en-US')
    chrome_options.add_experimental_option('prefs', {'intl.accept_languages': 'en-US'})

    # managed_default_content_settings.images = 2: Disable images load, this setting can improve pageload & save bandwidth
    # default_content_setting_values.notifications = 2: Disable notifications
    # credentials_enable_service & password_manager_enabled = false: Ignore save password prompt from chrome
    chrome_prefs = {
      'intl.accept_languages': 'en-US',
      'profile.managed_default_content_settings.images': 2,
      'profile.default_content_setting_values.notifications': 2,
      'credentials_enable_service': False,
      'profile': {
        'password_manager_enabled': False
      }
    }
    chrome_options.add_experimental_option('prefs', chrome_prefs)

    self.browser = webdriver.Chrome('./assets/chromedriver', chrome_options=chrome_options)
    self.browser.implicitly_wait(5)

    self.logFile = open('./logs/logFile.txt', 'a')
    self.logFile.write('Session started - %s\n' \
                       % (datetime.now().strftime('%Y-%m-%d %H:%M:%S')))

    if not username or not password:
      print('Please provide Username and Password')
      return

    self.username = username
    self.password = password
    self.nogui = nogui

    self.followed = 0

    self.ignore_users = []

    self.aborting = False
Example 23
Project: InstaPy   Author: timgrossmann   File: instapy.py View Source Project 4 votes vote downvote up
def set_selenium_local_session(self):
        """Starts local session for a selenium server.
        Default case scenario."""
        if self.aborting:
            return self

        if self.use_firefox:
            if self.firefox_profile_path is not None:
                firefox_profile = webdriver.FirefoxProfile(
                    self.firefox_profile_path)
            else:
                firefox_profile = webdriver.FirefoxProfile()

            # permissions.default.image = 2: Disable images load,
            # this setting can improve pageload & save bandwidth
            firefox_profile.set_preference('permissions.default.image', 2)

            self.browser = webdriver.Firefox(firefox_profile=firefox_profile)

        else:
            chromedriver_location = './assets/chromedriver'
            chrome_options = Options()
            chrome_options.add_argument('--dns-prefetch-disable')
            chrome_options.add_argument('--no-sandbox')
            chrome_options.add_argument('--lang=en-US')
            chrome_options.add_argument('--disable-setuid-sandbox')
            
            ## This option implements Chrome Headless, a new (late 2017) GUI-less browser
            ## Must be Chromedriver 2.9 and above.
            if self.headless_browser:
                chrome_options.add_argument('--headless')
                user_agent = "Chrome" # Replaces browser User Agent from "HeadlessChrome".
                chrome_options.add_argument('user-agent={user_agent}'.format(user_agent=user_agent))

            # managed_default_content_settings.images = 2: Disable images load,
            # this setting can improve pageload & save bandwidth
            # default_content_setting_values.notifications = 2:
            # Disable notifications
            # credentials_enable_service & password_manager_enabled = false:
            # Ignore save password prompt from chrome
            # 'profile.managed_default_content_settings.images': 2,
            # 'profile.default_content_setting_values.notifications' : 2,
            # 'credentials_enable_service': False,
            # 'profile': {
            #   'password_manager_enabled': False
            # }

            chrome_prefs = {
                'intl.accept_languages': 'en-US'
            }
            chrome_options.add_experimental_option('prefs', chrome_prefs)
            self.browser = webdriver.Chrome(chromedriver_location,
                                            chrome_options=chrome_options)
        self.browser.implicitly_wait(self.page_delay)
        self.logger.info('Session started - %s'
                         % (datetime.now().strftime('%Y-%m-%d %H:%M:%S')))

        return self
Example 24
Project: jibri   Author: jitsi   File: jibriselenium.py View Source Project 4 votes vote downvote up
def __init__(self, 
            url, 
            authtoken=None, 
            xmpp_connect_timeout=10, 
            binary_location=None, 
            google_account=None,
            google_account_password=None, 
            displayname='Live Stream', 
            email='recorder@jitsi.org',
            xmpp_login = None,
            xmpp_password = None,
            pjsua_flag = False):

      #init based on url and optional token
      self.url = url
      self.authtoken = authtoken
      self.google_account = google_account
      self.google_account_password = google_account_password
      self.displayname = displayname
      self.xmpp_login = xmpp_login
      self.xmpp_password = xmpp_password
      self.email = email
      self.pjsua_flag = pjsua_flag

      self.flag_jibri_identifiers_set = False
      self.flag_google_login_set = False

      #only wait this only before failing to load meet
      self.xmpp_connect_timeout = xmpp_connect_timeout

      self.desired_capabilities = DesiredCapabilities.CHROME
      self.desired_capabilities['loggingPrefs'] = { 'browser':'ALL' }

      self.options = Options()
      self.options.add_argument('--use-fake-ui-for-media-stream')
      self.options.add_argument('--start-maximized')
      self.options.add_argument('--kiosk')
      self.options.add_argument('--enabled')
      self.options.add_argument('--enable-logging')
      self.options.add_argument('--vmodule=*=3')
      self.options.add_argument("--disable-infobars")      
      self.options.add_argument('--alsa-output-device=plug:amix')

      #use microphone if provided
      if self.pjsua_flag:
        self.options.add_argument('--alsa-input-device=plughw:1,1')
        self.xmpp_login=None
        self.xmpp_password=None

      if binary_location:
        self.options.binary_location = binary_location
      self.initDriver()
Example 25
Project: biweeklybudget   Author: jantman   File: screenscraper.py View Source Project 4 votes vote downvote up
def get_browser(self, browser_name):
        """get a webdriver browser instance """
        self._browser_name = browser_name
        if browser_name == 'firefox':
            logger.debug("getting Firefox browser (local)")
            if 'DISPLAY' not in os.environ:
                logger.debug("exporting DISPLAY=:0")
                os.environ['DISPLAY'] = ":0"
            browser = webdriver.Firefox()
        elif browser_name == 'chrome':
            logger.debug("getting Chrome browser (local)")
            browser = webdriver.Chrome()
            browser.set_window_size(1920, 1080)
            browser.implicitly_wait(2)
        elif browser_name == 'chrome-headless':
            logger.debug('getting Chrome browser (local) with --headless')
            chrome_options = Options()
            chrome_options.add_argument("--headless")
            browser = webdriver.Chrome(chrome_options=chrome_options)
            browser.set_window_size(1920, 1080)
            browser.implicitly_wait(2)
        elif browser_name == 'phantomjs':
            logger.debug("getting PhantomJS browser (local)")
            dcap = dict(DesiredCapabilities.PHANTOMJS)
            dcap["phantomjs.page.settings.userAgent"] = self.user_agent
            args = [
                '--cookies-file={c}'.format(c=self._cookie_file),
                '--ssl-protocol=any',
                '--ignore-ssl-errors=true',
                '--web-security=false'
            ]
            browser = webdriver.PhantomJS(
                desired_capabilities=dcap, service_args=args
            )
            browser.set_window_size(1024, 768)
        else:
            raise SystemExit(
                "ERROR: browser type must be one of 'firefox', 'chrome', "
                "'chrome-headless' or 'phantomjs', not '{b}'".format(
                    b=browser_name
                )
            )
        logger.debug("returning browser")
        return browser 
Example 26
Project: timestrap   Author: overshard   File: tests_selenium.py View Source Project 4 votes vote downvote up
def setUpClass(cls):
        call_command('migrate', verbosity=0)
        cls.profile = fake.simple_profile()
        cls.profile['password'] = fake.password()
        super(SeleniumTestCase, cls).setUpClass()

        # Using saucelabs for CI testing since travis CI is inconsistent while
        # using selenium.
        if os.environ.get('SAUCE_USERNAME', None):
            sauce_username = os.environ['SAUCE_USERNAME']
            sauce_access_key = os.environ['SAUCE_ACCESS_KEY']
            sauce_url = 'http://' + sauce_username + ':' + sauce_access_key + \
                        '@ondemand.saucelabs.com/wd/hub'
            desired_capabilities = {
                'browserName': 'chrome',
                'version': '58',
                'platform': 'ANY',
                'chromeOptions': {
                    'prefs': {
                        'credentials_enable_service': False,
                        'profile': {
                            'password_manager_enabled': False
                        }
                    }
                }
            }
            if os.environ.get('TRAVIS_JOB_NUMBER', None):
                desired_capabilities.update({
                    'tunnel-identifier': os.environ['TRAVIS_JOB_NUMBER'],
                    'build': os.environ['TRAVIS_BUILD_NUMBER'],
                    'tags': [os.environ['TRAVIS_PYTHON_VERSION'], 'CI']
                })
            cls.driver = webdriver.Remote(
                command_executor=sauce_url,
                desired_capabilities=desired_capabilities
            )
        else:
            try:
                options = Options()
                if os.environ.get('GOOGLE_CHROME_BINARY', None):
                    options.binary_location = \
                        os.environ['GOOGLE_CHROME_BINARY']
                options.add_argument('--headless')
                options.add_argument('--disable-gpu')
                options.add_argument('--no-sandbox')
                options.add_argument('--log-level=3')
                options.add_argument('--window-size=1280,720')
                cls.driver = webdriver.Chrome(chrome_options=options)
            except WebDriverException:
                cls.driver = webdriver.Firefox()

        cls.driver.implicitly_wait(10)
        cls.wait_time = 5
Example 27
Project: YOHO_Automated_Test   Author: yzwy1988   File: executer.py View Source Project 4 votes vote downvote up
def launch_browser():

    if env.RUNNING_BROWSER.upper() == "FIREFOX":
        # the end of the browser process , the end of the browser driven process
        os.popen("TASKKILL /F /IM firefoxdriver.exe")

        fp = FirefoxProfile()
        fp.native_events_enabled = False

        binary_path = PublicImp.common.get_value_from_conf("FIREFOX_BINARY_PATH")

        if binary_path == "":
            env.driver = selenium.webdriver.Firefox(firefox_profile=fp)
        else:
            fb = FirefoxBinary(firefox_path=binary_path)
            env.driver = selenium.webdriver.Firefox(firefox_profile=fp, firefox_binary=fb)

    elif env.RUNNING_BROWSER.upper() == "CHROME":
        os.popen("TASKKILL /F /IM chromedriver.exe")

        binary_path = PublicImp.common.get_value_from_conf("CHROME_BINARY_PATH")
        chromedriver = PublicImp.common.get_value_from_conf("DRIVER_CHROME")

        if binary_path == "":
            os.environ["webdriver.chrome.driver"] = chromedriver
            env.driver = selenium.webdriver.Chrome(executable_path=chromedriver)
        else:
            opts = Options()
            opts.binary_location = binary_path
            os.environ["webdriver.chrome.driver"] = chromedriver
            env.driver = selenium.webdriver.Chrome(executable_path=chromedriver, chrome_options=opts)

    elif env.RUNNING_BROWSER.upper() == "IE":
        os.popen("TASKKILL /F /IM IEDriverServer.exe")

        dc = DesiredCapabilities.INTERNETEXPLORER.copy()

        dc['acceptSslCerts'] = True
        dc['nativeEvents'] = True

        iedriver = PublicImp.common.get_value_from_conf("DRIVER_IE")
        os.environ["webdriver.ie.driver"] = iedriver
        env.driver = selenium.webdriver.Ie(executable_path=iedriver, capabilities=dc)

    else:
        return False

    env.platformName = env.RUNNING_BROWSER

    env.TEST_URL = PublicImp.common.get_value_from_conf("TESTING_URL")
    env.driver.get(env.TEST_URL)
    env.driver.maximize_window()

    time.sleep(3)
    env.driver.refresh()
    # env.driver.set_window_size(480, 800)
    time.sleep(3)

    return True
posted @ 2018-03-15 11:12  公众号python学习开发  阅读(9907)  评论(0编辑  收藏  举报