How to use the selenium.webdriver.Chrome function in selenium

To help you get started, we’ve selected a few selenium examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pde / https-everywhere / test / chromium / script.py View on Github external
chromeOps.add_argument('--disable-setuid-sandbox')
elif sys.platform.startswith("linux"):
    if 'Ubuntu' in platform.linux_distribution():
        chromedriver_path = "/usr/lib/chromium-browser/chromedriver"
    elif 'debian' in platform.linux_distribution():
        #Debian is lowercase when platform.linux_distribution() is used.
        #This is not a mistake.
        chromedriver_path = "/usr/lib/chromium/chromedriver"
else:
    # Let's hope it's in the user's path.
    chromedriver_path = "chromedriver"


try:
    # First argument is optional, if not specified will search path.
    driver = webdriver.Chrome(chromedriver_path, chrome_options=chromeOps)
except WebDriverException as e:
    error = e.__str__()

    if "executable needs to be in PATH" in e.__str__():
        print "ChromeDriver isn't installed. Check test/chrome/README.md " \
              "for instructions on how to install ChromeDriver"

        sys.exit(2)
    else:
        raise e

print ''

driver.get('http://libssh.org/robots.txt')

test_failed = False
github SergeyPirogov / webdriver_manager / tests / test_driver_manager.py View on Github external
def test_chrome_manager_with_selenium():
    driver_path = ChromeDriverManager().install()
    webdriver.Chrome(driver_path)
github yang / flight-scraper / flightscraper / __init__.py View on Github external
cfg.outdir.mkdir_p()

  # find unused display; note TOCTTOU
  for display in itr.count():
    if not path.path('/tmp/.X11-unix/X%s' % display).exists():
      break

  try:
    cmd = 'sleep 99999999' if cfg.debug else 'Xvfb :%s -screen 0 1600x1200x24' % display
    with subproc(cmd.split()) as xvfb:
      if not cfg.debug: os.environ['DISPLAY'] = ':%s' % display
      # This silencing isn't working
      stdout, stderr = sys.stdout, sys.stderr
      sys.stdout = open('/dev/null','w')
      sys.stderr = open('/dev/null','w')
      with quitting(webdriver.Chrome()) as wd:
        sys.stdout, sys.stderr = stdout, stderr
        email_text, email_html, raw_res = script(wd, cfg)

    with open(cfg.outdir / 'results.pickle', 'w') as f: pickle.dump(raw_res, f, 2)

    if cfg.mailto:
      mail = MIMEMultipart('alternative')
      mail['From'] = cfg.mailfrom
      mail['To'] = cfg.mailto
      mail['Subject'] = 'Flight Scraper Results for %s' % fmt_time(now)
      mail.attach(MIMEText(email_text, 'plain'))
      mail.attach(MIMEText(email_html, 'html'))
      with contextlib.closing(smtplib.SMTP('localhost')) as smtp:
        smtp.sendmail(mail['From'], mail['To'].split(','), mail.as_string())
  except:
    msg = '%s\n\n%s' % (traceback.format_exc(),
github nevikw39 / ZeroJudge_Exporter / ZeroJudge_Exporter.py View on Github external
def bar():
    lang = {'C': '.c', 'CPP': '.cpp', 'PYTHON': '.py'}
    path = filedialog.askdirectory()
    for i in d:
        x = 1
        name = path + '/' + i[:4]
        while os.path.exists(name + lang[d[i]['lang']]):
            name = '{}/{}-{}'.format(path, i[:4], x)
            x += 1
        name += lang[d[i]['lang']]
        with open(name, 'w') as f:
            f.write(d[i]['code'])
    messagebox.showinfo("Info", '儲存成功')

try:
    browser = webdriver.Chrome()  # 初始化瀏覽器
except WebDriverException:
    messagebox.showerror("Error", "找不到 Chrome Driver")
    sys.exit()
tk = tkinter.Tk()  # 初始化視窗
tk.title('ZeroJudge 匯出下載工具')
tree = ttk.Treeview(tk, columns=('num', 'date', 'result', 'lang'))
tree.heading('#0', text='title')
tree.heading('#1', text='num')
tree.heading('#2', text='date')
tree.heading('#3', text='result')
tree.heading('#4', text='lang')
tree.column('#0')
tree.column('#1', width=100)
tree.column('#2', width=100)
tree.column('#3', width=100)
tree.column('#4', width=100)
github abhishek-vinjamoori / SubtitleExtractor / setup.py View on Github external
parser.optionxform = str
    customerUrl = parser.get(parsingDictionary['service'], 'customerurl')
    tokenUrl = parser.get(parsingDictionary['service'], 'tokenurl')

    xpaths = {'usernameBox': "//*[@id='ap_email']",
              'passwordBox': "//*[@id='ap_password']",
              'submitButton':   "//*[@id='signInSubmit']"
              }

    firefox_profile = webdriver.FirefoxProfile()
    firefox_profile.set_preference('permissions.default.stylesheet', 2)
    firefox_profile.set_preference('permissions.default.image', 2)
    firefox_profile.set_preference(
        'dom.ipc.plugins.enabled.libflashplayer.so', 'false')

    amazonDriver = webdriver.Chrome()
    amazonDriver.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:36.0) Gecko/20100101 Firefox/36.0 WebKit'
    amazonDriver.cookiesEnabled = True
    amazonDriver.javascriptEnabled = True
    amazonDriver.get(baseurl)
    # Clearing Username TextBox
    amazonDriver.find_element_by_xpath(xpaths['usernameBox']).clear()

    # Typing in the username as obtained from config file
    amazonDriver.find_element_by_xpath(
        xpaths['usernameBox']).send_keys(username)

    # Clearing password field
    amazonDriver.find_element_by_xpath(xpaths['passwordBox']).clear()

    # Typing in the password
    amazonDriver.find_element_by_xpath(
github intoli / intoli-article-materials / articles / javascript-injection / selenium-mitmproxy.py View on Github external
# Loop through the four different configurations.
for browser in ['chrome', 'firefox']:
    for mode in ['headless', 'graphical']:
        # Set up the driver with the appropriate settings.
        if browser == 'chrome':
            # Enable headless mode.
            options = webdriver.ChromeOptions()
            if mode == 'headless':
                options.add_argument('--headless')

            # Specify the proxy.
            options.add_argument('--proxy-server=%s:%s' % (proxy_host, proxy_port))

            # Launch Chrome.
            driver = webdriver.Chrome(chrome_options=options)

        elif browser == 'firefox':
            # Enable headless mode.
            if mode == 'headless':
                os.environ['MOZ_HEADLESS'] = '1'
            elif mode == 'graphical':
                os.environ.pop('MOZ_HEADLESS', None)

            firefox_profile = webdriver.FirefoxProfile()
            # Specify to use manual proxy configuration.
            firefox_profile.set_preference('network.proxy.type', 1)
            # Set the host/port.
            firefox_profile.set_preference('network.proxy.http', proxy_host)
            firefox_profile.set_preference('network.proxy.https_port', proxy_port)
            firefox_profile.set_preference('network.proxy.ssl', proxy_host)
            firefox_profile.set_preference('network.proxy.ssl_port', proxy_port)
github elvisyjlin / lf2gym / lib / seleniumdriver.py View on Github external
# driver = webdriver.PhantomJS(service_args=["--remote-debugger-port=9000", "--web-security=false"])
    elif driverType == 'Chrome':
        desired = DesiredCapabilities.CHROME
        desired['loggingPrefs'] = {'browser': 'ALL'}
        chrome_options = Options()
        chrome_options.add_argument("--start-maximized")
        chrome_options.add_argument("--disable-infobars")
        chrome_options.add_argument("--disable-web-security")
        # chrome_options.add_argument("--window-size=800,600")
        if headless:
            chrome_options.add_argument("--headless") # will not show the Chrome browser window
        if localDriver:
            source = get_source(driverType, path)
            driver = webdriver.Chrome(executable_path=source, service_log_path=join(path, 'chromedriver.log'), desired_capabilities=desired, chrome_options=chrome_options)
        else:
            driver = webdriver.Chrome(service_log_path=join(path, 'chromedriver.log'), desired_capabilities=desired, chrome_options=chrome_options)
    elif driverType == 'Firefox':
        # desired = DesiredCapabilities.FIREFOX
        # desired['loggingPrefs'] = {'browser': 'ALL'}
        firefox_options = Options()
        firefox_options.add_argument("--start-maximized")
        firefox_options.add_argument("--disable-infobars")
        if localDriver:
            source = get_source(driverType, path)
            driver = webdriver.Firefox(executable_path=source, service_log_path=join(path, 'geckodriver.log'), firefox_options=firefox_options)
        else:
            driver = webdriver.Firefox(service_log_path=join(path, 'geckodriver.log'), firefox_options=firefox_options)
    return driver
github brutemap-dev / brutemap / lib / settings.py View on Github external
${html_table}
    
\
""")

SEPARATOR_REGEX = r"[,\s]*"

EMAIL_REGEX = r"[\w.-]+@[\w.-]+"

URL_SCHEMES = ("http://", "https://")

SPINNER_CHARS = ["|", "/", "-", "\\"]

WEB_DRIVER = {
    "firefox": Firefox,
    "chrome": Chrome,
    "gtk": WebKitGTK,
    "edge": Edge,
    "ie": Ie,
    "safari": Safari,
    "phantomjs": PhantomJS,
    "android": Android
}

IS_PY3K = sys.version_info[0] == 3

# for python 3.4, because it doesn't have the mswindows attribute.
IS_WINDOWS = sys.platform.startswith("win")
github OmarEinea / GoodReadsScraper / Browser.py View on Github external
def __init__(self, edition_reviews=False):
        Chrome.__init__(self, desired_capabilities=self.OPTIONS)
        # Set page loading timeout to 30 seconds
        self.set_page_load_timeout(30)
        self.edition_reviews = edition_reviews
        # Initialize browsing counters
        self.rating = self.sort = self.fails = None
github mdrichardson / FUTpuppeteer / FUTpuppeteer / core.py View on Github external
pass
                    # self.opts.add_argument('--headless')
                    # self.opts.add_argument('--disable-gpu')
                if self.proxy:
                    self.opts.add_argument("--proxy-server={0}".format(self.proxy))
                # Install chrome extensions if they don't exist
                if not disable_extensions:
                    ublock = 'cjpalhdlnbpafiamejdnhcphjbkeiagm'
                    futbin = 'adicaaffkmhgnfheifkjhopmambgfihl'
                    if not os.path.exists(self.userdir + '/Default/Extensions/' + ublock):
                        multi_log(self, 'Installing ublock extension...', level='debug')
                        self.opts.add_extension('extensions/ublock.crx')
                    if not os.path.exists(self.userdir + '/Default/Extensions/' + futbin):
                        multi_log(self, 'Installing futbin extension...', level='debug')
                        self.opts.add_extension('extensions/futbin.crx')
                self.driver = webdriver.Chrome(executable_path=Global.path_to_chromedriver_exe, chrome_options=self.opts)
                if headless:
                    self.driver.set_window_position(-10000, 0)
                break
            except WebDriverException as e:
                multi_log(self, e, level='error', notify=False)
                multi_log(self, 'Failed to start: {}'.format(e), level='error')
                if 'failed to start' in str(e).lower():
                    raise Exception('Please close all windows for this bot before trying again. You may need to close out of ALL chrome instances to continue')
                self.keep_alive(5)
        if not delay_login:
            self.__login__()
        # Get this chromedriver PID so we can force-close it as needed
        self.pid = []
        for process in psutil.process_iter():
            if 'chromedriver' in process.name() and process.pid not in pids and time() - process.create_time() < 100:
                self.pid.append(process.pid)