コード例 #1
0
ファイル: install_test.py プロジェクト: fengjixuchui/h5vcc
    def StartChrome(self, caps={}):
        """Creates a ChromeDriver instance.

    Args:
      caps: Capabilities that will be passed to ChromeDriver.
    """
        self._driver = Chrome(self._service.service_url, caps)
コード例 #2
0
  def StartChrome(self, caps={}, options=None):
    """Creates a ChromeDriver instance.

    If both caps and options have the same settings, the settings from options
    will be used.

    Args:
      caps: Capabilities that will be passed to ChromeDriver.
      options: ChromeOptions object that will be passed to ChromeDriver.
    """
    self._driver = Chrome(self._service.service_url, caps, options)
コード例 #3
0
    def refresh(self, widget=None, no_timer=False, chrome_data_directory=None, firefox_data_directory=None):

        """Refreshes the menu """
        try:
            # Create an array of 20 false to denote matches in History
            searchResults = [False] * 20
            data = list(reversed(HackerNews.getHomePage()[0:20]))
            urls = [item['url'] for item in data]
            if chrome_data_directory:
                searchResults = self.mergeBoolArray(searchResults, Chrome.search(urls, chrome_data_directory))

            if firefox_data_directory:
                searchResults = self.mergeBoolArray(searchResults, Firefox.search(urls, firefox_data_directory))

            # Remove all the current stories
            for i in self.menu.get_children():
                if hasattr(i, 'url'):
                    self.menu.remove(i)

            # Add back all the refreshed news
            for index, item in enumerate(data):
                item['history'] = searchResults[index]
                if item['url'].startswith('item?id='):
                    item['url'] = "https://news.ycombinator.com/" + item['url']

                self.addItem(item)
        # Catch network errors
        except requests.exceptions.RequestException as e:
            print "[+] There was an error in fetching news items"
        finally:
            # Call every 10 minutes
            if not no_timer:
                gtk.timeout_add(10 * 30 * 1000, self.refresh, widget, no_timer, chrome_data_directory)
コード例 #4
0
  def StartChrome(self, caps={}):
    """Creates a ChromeDriver instance.

    Args:
      caps: Capabilities that will be passed to ChromeDriver.
    """
    self._driver = Chrome(self._service.service_url, caps)
コード例 #5
0
def log():
    print e.get()
    number = e.get()
    if number == '':
        show_tip()
    else:
        key = Http.get_key(number)
        print key

        if key == '':
            show_code_error()
        else:
            print key

            root.withdraw()
            chrome = Chrome(key)
            chrome.open_web()
コード例 #6
0
 def __init__(self):
     self.ss = requests.session()
     chrome = Chrome()
     cookies = chrome.cookie('.baidu.com')
     self.ss.cookies.update(cookies)
     baseheaders = {
         'Accept': 'application/json, text/plain, */*',
         'Accept-Encoding': 'gzip, deflate',
         'Accept-Language': 'zh-CN,zh;q=0.9',
         'Cache-Control': 'no-cache',
         'DNT': '1',
         'Host': 'index.baidu.com',
         'Pragma': 'no-cache',
         'Referer': 'http://index.baidu.com/v2/main/index.html',
         'User-Agent':
         'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
         'X-Requested-With': 'XMLHttpRequest',
     }
     self.ss.headers.update(baseheaders)
コード例 #7
0
def main():
    print("Blink Container Main script")

    #Change the working directory to the Shared folder
    os.chdir(Container.homeFolder)

    if os.path.isfile(Container.updateFile):
        #We update the container
        subprocess.call(["python3", "/home/blink/updateContainer.py"])
    else:
        #We create an instance of Container
        blink = Container()

        #We check the Data file with the complete user profile
        blink.checkDataFile()

        #We chose the fonts and the plugins
        blink.selectFonts()
        blink.selectPlugins()

        if blink.selectBrowser() == 'chrome':
            browser = Chrome()
        else:
            browser = Firefox()
        #We import the user profile inside the browser
        browser.importData()

        #We initialise a boolean to indicate if the
        #VM must be shutdown
        shutdown = False

        while not shutdown:
            #We launch the browser
            browserProcess = browser.runBrowser()
            signal.signal(signal.SIGINT, sigint_handler)
            #We wait for either the browsing session to be finished
            while not isinstance(browserProcess.poll(), int):
                time.sleep(1)

            encryption = browser.exportData()

            #Encrypt file if the encryption is activated
            if encryption:
                done = False
                while not done:
                    res = subprocess.getstatusoutput(
                        "gpg2 -c --cipher-algo=AES256 " + Container.dataFile)
                    if res[0] == 0:
                        #If the encryption went well, we removed the unencrypted file
                        subprocess.call("rm " + Container.dataFile, shell=True)
                        done = True
                    elif "cancelled" in res[1]:
                        #If the user cancelled the encryption operation, we do nothing
                        done = True

            #We finish the execution of the script
            shutdown = True
コード例 #8
0
def main():
    print("Blink Container Main script")

    #Change the working directory to the Shared folder
    os.chdir(Container.homeFolder)

    if os.path.isfile(Container.updateFile):
        #We update the container
        subprocess.call(["python3","/home/blink/updateContainer.py"])
    else :
        #We create an instance of Container
        blink = Container()

        #We check the Data file with the complete user profile
        blink.checkDataFile()

        #We chose the fonts and the plugins
        blink.selectFonts()
        blink.selectPlugins()

        if blink.selectBrowser() == 'chrome':
            browser = Chrome()
        else :
            browser = Firefox()
        #We import the user profile inside the browser
        browser.importData()

        #We initialise a boolean to indicate if the
        #VM must be shutdown
        shutdown = False

        while not shutdown :
            #We launch the browser
            browserProcess = browser.runBrowser()
            signal.signal(signal.SIGINT, sigint_handler)
            #We wait for either the browsing session to be finished
            while not isinstance(browserProcess.poll(),int):
                time.sleep(1)


            encryption = browser.exportData()

            #Encrypt file if the encryption is activated
            if encryption :
                done = False
                while not done :
                    res = subprocess.getstatusoutput("gpg2 -c --cipher-algo=AES256 "+Container.dataFile)
                    if res[0] == 0 :
                        #If the encryption went well, we removed the unencrypted file
                        subprocess.call("rm "+Container.dataFile,shell=True)
                        done = True
                    elif "cancelled" in res[1]:
                        #If the user cancelled the encryption operation, we do nothing
                        done = True

            #We finish the execution of the script
            shutdown = True
コード例 #9
0
ファイル: media.py プロジェクト: LiZoRN/flyadb
    def __init__(self, device, mod):
        self.product = Configs("common").get("product", "Info")
        self.device = connect_device(device)
        self.appconfig = AppConfig("appinfo")
        self.logger = createlogger(mod)
        self.camera = Camera(self.device, "media_camera")
        self.record = Recorder(self.device, "media_recorder")
        #self.browser = Browser(self.device,"media_browser")
        self.chrome = Chrome(self.device, "media_chrome")
        if self.product == "Sprints":
            self.music = PlayMusic(self.device, "media_music")
        else:
            self.music = Music(self.device, "media_music")
        self.suc_times = 0
        self.mod_cfg = GetConfigs(mod)
        self.test_times = 0
        self.dicttesttimes = self.mod_cfg.get_test_times()

        for i in self.dicttesttimes:
            self.test_times += int(self.dicttesttimes[i])
            if i.upper() in ('VIDEOTIMES', 'RECORDER', 'PHOTOTIMES'):
                self.test_times += int(self.dicttesttimes[i]) * 2
        self.logger.info('Trace Total Times ' + str(self.test_times))
コード例 #10
0
ファイル: main.py プロジェクト: jinyb09017/tvshow
# coding:utf-8
from http import Http
from chrome import Chrome

key = Http.get_key_new()
print key

if key == '':
    print "验证码错误"
else:
    print key

chrome = Chrome(key)
chrome.open_web_up()
input("wait....")
コード例 #11
0
from chrome import Chrome
import coinmarketcap

if __name__ == '__main__':

    chrome = Chrome()
    coinmarketcap.run(chrome)
    chrome.web.close()
コード例 #12
0
class InstallTest(unittest.TestCase):
  """Base updater test class.

  All dependencies, like Chrome installers and ChromeDriver, are downloaded at
  the beginning of the test. Dependencies are downloaded in the temp directory.
  This download occurs only once, before the first test is executed. Each test
  case starts an instance of ChromeDriver and terminates it upon completion.
  All updater tests should derive from this class.

  Example:

  class SampleUpdater(InstallTest):

    def testCanOpenGoogle(self):
      self.Install(self.GetUpdateBuilds()[0])
      self.StartChrome()
      self._driver.get('http://www.google.com/')
      self.Install(self.GetUpdateBuilds()[1])
      self.StartChrome()
      self._driver.get('http://www.google.org/')

  Include the following in your updater test script to make it run standalone.

  from install_test import Main

  if __name__ == '__main__':
    Main()

  To fire off an updater test, use the command below.
    python test_script.py --url=<URL> --update-builds=24.0.1299.0,24.0.1300.0
  """

  _installer_paths = {}
  _chrome_driver = ''
  _installer_options = []
  _install_type = chrome_installer_win.InstallationType.USER

  def __init__(self, methodName='runTest'):
    unittest.TestCase.__init__(self, methodName)
    self._driver = None
    current_version = chrome_installer_win.ChromeInstallation.GetCurrent()
    if current_version:
      current_version.Uninstall()

  def setUp(self):
    """Called before each unittest to prepare the test fixture."""
    self._StartService()

  def tearDown(self):
    """Called at the end of each unittest to do any test related cleanup."""
    # Confirm ChromeDriver was instantiated, before attempting to quit.
    if self._driver is not None:
      try:
        self._driver.quit()
      except WebDriverException:
        pass
    self._service.stop()
    self._installation.Uninstall()

  def _StartService(self):
    """Starts ChromeDriver service."""
    self._service = service.Service(InstallTest._chrome_driver)
    self._service.start()

  def StartChrome(self, caps={}, options=None):
    """Creates a ChromeDriver instance.

    If both caps and options have the same settings, the settings from options
    will be used.

    Args:
      caps: Capabilities that will be passed to ChromeDriver.
      options: ChromeOptions object that will be passed to ChromeDriver.
    """
    self._driver = Chrome(self._service.service_url, caps, options)

  def Install(self, build, master_pref=None):
    """Helper method that installs the specified Chrome build.

    Args:
      build: Chrome version number that will be used for installation.
      master_pref: Location of the master preferences file.
    """
    if self._driver:
      try:
        self._driver.quit()
      except WebDriverException:
        pass
    options = []
    options.extend(self._installer_options)
    if self._install_type == chrome_installer_win.InstallationType.SYSTEM:
      options.append('--system-level')
    if master_pref:
      options.append('--installerdata=%s' % master_pref)
    self._installation = chrome_installer_win.Install(
        self._installer_paths[build],
        self._install_type,
        build,
        options)

  def GetInstallBuild(self):
    """Returns Chorme build to be used for install test scenarios."""
    return self._install_build

  def GetUpdateBuilds(self):
    """Returns Chrome builds to be used for update test scenarios."""
    return self._update_builds

  @staticmethod
  def _Download(url, path):
    """Downloads a file from the specified URL.

    Args:
      url: URL where the file is located.
      path: Location where file will be downloaded.

    Raises:
      RuntimeError: URL or file name is invalid.
    """
    if not util.DoesUrlExist(url):
      raise RuntimeError('Either the URL or the file name is invalid.')
    urllib.urlretrieve(url, path)

  @staticmethod
  def SetInstallType(install_type):
    """Sets Chrome installation type.

    Args:
      install_type: Type of installation(i.e., user or system).
    """
    InstallTest._install_type = install_type

  @staticmethod
  def InitTestFixture(install_build, update_builds, base_url, options):
    """Static method for passing command options to InstallTest.

    We do not instantiate InstallTest. Therefore, command arguments cannot be
    passed to its constructor. Since InstallTest needs to use these options,
    and using globals is not an option, this method can be used by the Main
    class to pass the arguments it parses onto InstallTest.

    Args:
      install_build: A string representing the Chrome build to be used for
                     install testing. Pass this argument only if testing
                     fresh install scenarios.
      update_builds: A list that contains the Chrome builds to be used for
                     testing update scenarios. Pass this argument only if
                     testing upgrade scenarios.
      base_url: Base url of the 'official chrome builds' page.
      options: A list that contains options to be passed to Chrome installer.
    """
    system = util.GetPlatformName()
    InstallTest._install_build = install_build
    InstallTest._update_builds = update_builds
    InstallTest._installer_options = options
    tempdir = util.MakeTempDir()
    builds = []
    if InstallTest._install_build:
      builds.append(InstallTest._install_build)
    if InstallTest._update_builds:
      builds.extend(InstallTest._update_builds)
    # Remove any duplicate build numbers.
    builds = list(frozenset(builds))
    for build in builds:
      url = '%s%s/%s/mini_installer.exe' % (base_url, build, system)
      installer_path = os.path.join(tempdir, 'mini_installer_%s.exe' % build)
      InstallTest._installer_paths[build] = installer_path
      InstallTest._Download(url, installer_path)
    InstallTest._chrome_driver = os.path.join(tempdir, 'chromedriver.exe')
    url = '%s%s/%s/%s/chromedriver.exe' % (base_url, build, system,
                                           'chrome-win32.test')
    InstallTest._Download(url, InstallTest._chrome_driver)
コード例 #13
0
import time

from chrome import Chrome
import Page
import Runtime

c = Chrome()
c.do(Page.navigate("http://adhocteam.us/our-team"))

# if we don't wait for the page to load, then we can run the script too
# early and get an empty array.
#
# TODO a great next step would be to figure out how to receive pageLoad
#      event from Page and only run the command at that time
time.sleep(2)

cmd = '[].map.call(document.querySelectorAll("h3.centered"), n => n.textContent)'
c.do(Runtime.evaluate(cmd, returnByValue=True))
コード例 #14
0
ファイル: mainVM.py プロジェクト: DIVERSIFY-project/blink
def main():
	print("Blink VM Main script")

	#Change the working directory to the Shared folder
	os.chdir(VM.sharedFolder)

	#We create an instance of a VM
	machine = VM()

	#We chose the fonts and the plugins
	machine.selectFonts()
	machine.selectPlugins()

	#We look for the JSON data file
	dataPath = VM.jsonDataFile
	encryptedDataPath = dataPath+".gpg"

	#Decrypt file if encrypted
	if os.path.isfile(encryptedDataPath):
		cancelled = False
		while not os.path.isfile(dataPath) and not cancelled:
			res = subprocess.getstatusoutput("gpg2 -d -o "+dataPath+" "+encryptedDataPath)
			if res[0] != 0 and "cancelled" in res[1]:
				cancelled = True
		subprocess.call("rm "+encryptedDataPath,shell=True)

	#Look in the browser folder for the browser but
	#Execute a different command according to the browser used
	if os.path.isfile(VM.sharedFolder+"chrome.browser"):
		browser = Chrome()
	else :
		browser = Firefox()

	#We import the user profile inside the browser
	browser.importData()

	#We initialise a boolean to indicate if the
	#VM must be shutdown
	shutdown = False

	while not shutdown :
		#We launch the browser
		browserProcess = browser.runBrowser()

		#We wait for either the browsing session to be finished or the computer to be locked
		while not isinstance(browserProcess.poll(),int) and not os.path.isfile(VM.sharedFolder+"browser.switch"):
			time.sleep(10)

		encryption = browser.exportData()

		#If the browsing session is finished
		if isinstance(browserProcess.poll(),int) :
			#Encrypt file if the encryption is activated
			if encryption :
				done = False
				while not done :
					res = subprocess.getstatusoutput("gpg2 -c --cipher-algo=AES256 "+dataPath)
					if res[0] == 0 :
						#If the encryption went well, we removed the unencrypted file
						subprocess.call("rm "+dataPath,shell=True)
						done = True
					elif "cancelled" in res[1]:
						#If the user cancelled the encryption operation, we do nothing
						done = True

			#We write a file to signal the host to shutdown all running VMs
			subprocess.call("touch "+VM.sharedFolder+"VM.shutdown", shell=True)

			#We finish the execution of the script
			shutdown = True

		else :
			#We terminate the browser process
			browserProcess.kill()

			#We switch the list of plugins and fonts
			machine.selectFonts()
			machine.selectPlugins()

			#We remove the "browser.switch" file
			subprocess.call("rm "+VM.sharedFolder+"browser.switch",shell=True)
コード例 #15
0
        _, _, count = driver.find_element_by_xpath(
            '//span[@data-region="user-count-summary"]').text.split(' ')
        return int(count)

    def calificaciones(self, course):
        driver = self.driver
        driver.get(self.base + '/my/')
        a = driver.find_element_by_xpath(
            '//a[normalize-space(text())="{}"]'.format(course))
        courseid = a.get_attribute('href').split('=')[1]
        driver.get(self.base + '/grade/export/xls/index.php?id=' + courseid)
        driver.find_element_by_id('id_submitbutton').click()
        self.chrome.download_file()


def get_element_value(e):
    if e.get_attribute('type') == 'checkbox':
        return str(int(e.is_selected()))
    return e.get_attribute('value')


if __name__ == '__main__':
    try:
        os.chdir(os.path.dirname(__file__))
    except:
        pass
    with Chrome() as b:
        cv = CampusVirtual(b)
        cv.authenticate()
        cv.calificaciones('REDES DE COMPUTADORES I')
コード例 #16
0
ファイル: webmail.py プロジェクト: jinsust/mail
# -*- coding: UTF-8 -*-
import time

from chrome import Chrome

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = 'http://webmail.kingxin.top'

cr = Chrome(False)


def get_webmail_cookie(username, password):
    cr.driver.get(url)
    wait = WebDriverWait(cr.driver, 10)
    input_mail = wait.until(
        EC.element_to_be_clickable((By.ID, 'RainLoopEmail')))
    input_mail.send_keys(username)
    input_pw = cr.driver.find_element_by_id('RainLoopPassword')
    input_pw.send_keys(password)

    button_login = cr.driver.find_element_by_class_name('buttonLogin')

    button_login.click()

    wait = WebDriverWait(cr.driver, 10)

    icon = wait.until(
コード例 #17
0
ファイル: mainVM.py プロジェクト: zhjou/blink
def main():
    print("Blink VM Main script")

    #Change the working directory to the Shared folder
    os.chdir(VM.sharedFolder)

    #We create an instance of a VM
    machine = VM()

    #We chose the fonts and the plugins
    machine.selectFonts()
    machine.selectPlugins()

    #We look for the JSON data file
    dataPath = VM.jsonDataFile
    encryptedDataPath = dataPath + ".gpg"

    #Decrypt file if encrypted
    if os.path.isfile(encryptedDataPath):
        cancelled = False
        while not os.path.isfile(dataPath) and not cancelled:
            res = subprocess.getstatusoutput("gpg2 -d -o " + dataPath + " " +
                                             encryptedDataPath)
            if res[0] != 0 and "cancelled" in res[1]:
                cancelled = True
        subprocess.call("rm " + encryptedDataPath, shell=True)

    #Look in the browser folder for the browser but
    #Execute a different command according to the browser used
    if os.path.isfile(VM.sharedFolder + "chrome.browser"):
        browser = Chrome()
    else:
        browser = Firefox()

    #We import the user profile inside the browser
    browser.importData()

    #We initialise a boolean to indicate if the
    #VM must be shutdown
    shutdown = False

    while not shutdown:
        #We launch the browser
        browserProcess = browser.runBrowser()

        #We wait for either the browsing session to be finished or the computer to be locked
        while not isinstance(browserProcess.poll(),
                             int) and not os.path.isfile(VM.sharedFolder +
                                                         "browser.switch"):
            time.sleep(10)

        encryption = browser.exportData()

        #If the browsing session is finished
        if isinstance(browserProcess.poll(), int):
            #Encrypt file if the encryption is activated
            if encryption:
                done = False
                while not done:
                    res = subprocess.getstatusoutput(
                        "gpg2 -c --cipher-algo=AES256 " + dataPath)
                    if res[0] == 0:
                        #If the encryption went well, we removed the unencrypted file
                        subprocess.call("rm " + dataPath, shell=True)
                        done = True
                    elif "cancelled" in res[1]:
                        #If the user cancelled the encryption operation, we do nothing
                        done = True

            #We write a file to signal the host to shutdown all running VMs
            subprocess.call("touch " + VM.sharedFolder + "VM.shutdown",
                            shell=True)

            #We finish the execution of the script
            shutdown = True

        else:
            #We terminate the browser process
            browserProcess.kill()

            #We switch the list of plugins and fonts
            machine.selectFonts()
            machine.selectPlugins()

            #We remove the "browser.switch" file
            subprocess.call("rm " + VM.sharedFolder + "browser.switch",
                            shell=True)
コード例 #18
0
ファイル: admin.py プロジェクト: jinsust/mail
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from PIL import Image
import pytesseract

import os

pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract'

url = 'http://admin.kingxin.top'

cr = Chrome(True)


def save_image(image_url):
    file_name = 'code.png'
    cmd = 'wget %s -O %s' % (image_url, file_name)
    os.system(cmd)
    return file_name


def image_orc(image_path):
    im = Image.open(image_path)
    '''
    im=im.convert('L')#图片转换为灰色图
    im=im.convert('RGBA')#图片转换成RGBA模式
    pixdata = im.load()
コード例 #19
0
context = {
    "assets": {
        "count": 5,
    },
    "company": {
        "name": "Flughafen Bern AG",
    },
    "assembly": {
        "name": "Generalversammlung der Flughafen Bern AG",
        "date": "4 Aug 2020",
        "address": "GV Flughafen Bern AG"
    },
    "shareholder": {
        "get_full_name": "Rudy Fasel Sarl",
        "get_stacked_address": "Rue Pontmurre 14",
    },
    "coupon_count": 15
}

settings.configure(**SETTINGS)

django.setup()

p = Chrome()

pdf = p.render_template("admission_card.pdf.html", context)

pdf_file = open("admission_card.pdf", 'wb')

pdf_file.write(pdf)