def connect_ie_driver(headless): """Function to connect with ie driver """ #initialise chrome options options = IeOptions() #set headless option on driver options.headless = headless #initialise driver driver = webdriver.Ie(IEDriverManager().install(), options=options) return driver
def connect_ie_driver(self): """Functions to connect with ie driver """ #initialise chrome options self.options = IeOptions() #add cookies on driver self.options.add_argument("user-data-dir=selenium") #initialise driver self.driver = webdriver.Ie(IEDriverManager().install(), ie_options=self.options) return self.driver
def browser_ie(browser_path="", driver_path=""): """ ie内核浏览器兼容, :param browser_path: 浏览器路径, :param driver_path: 驱动路径, :return: driver, """ global driver if len(browser_path) > 0: options = IeOptions() options.binary_location = browser_path else: options = None if len(driver_path) == 0 : driver_path = "IEDriverServer.exe" driver = webdriver.Ie(executable_path=driver_path, options=options) # 需要在设置-安全-四个区域中统一启用安全模式, return driver
def get_options(self): if self.get_type() == 'firefox': options = FirefoxOptions() if self.get_args(): for arg in self.get_args().split(): options.add_argument('--' + arg) if self.bin_path: options.binary_location(self.bin_path) if self.get_headless(): options.headless = True if self.get_window_size(): win_size = self.get_window_size().split(',') options.add_argument('--width=' + win_size[0]) options.add_argument('--height=' + win_size[1]) # Set download path options.set_preference('browser.download.folderList', 2) options.set_preference('browser.download.dir', get_download_path()) options.set_preference('browser.download.manager.showWhenStarting', False) options.set_preference('browser.helperApps.alwaysAsk.force', False) options.set_preference('browser.helperApps.neverAsk.saveToDisk', "application/octet-stream") # options.set_preference('browser.helperApps.neverAsk.openFile', "application/octet-stream") elif self.get_type() == 'ie': options = IeOptions() options.ignore_protected_mode_settings = False options.require_window_focus = True options.native_events = False # proceed IE options here else: options = ChromeOptions() if self.get_args(): for arg in self.get_args().split(): options.add_argument(arg) if self.bin_path: options.binary_location(self.bin_path) if self.get_headless(): options.headless = True if self.get_window_size(): options.add_argument('--window-size=' + self.get_window_size()) # Set download path prefs = {} prefs["download.prompt_for_download"] = 0 prefs["download.default_directory"] = get_download_path() options.add_experimental_option("prefs", prefs) return options
def getWebDriverInstance(self): baseURL = "https://learn.letskodeit.com/p/practice" if self.browser == "ie": driver_path = "C:\\DevTools\\webdriver\\IEDriverServer_win32_3.14.0.exe" os.environ["webdriver.ie.driver"] = driver_path options = IeOptions() options.binary_location = "C:\\Program Files\\internet explorer\\iexplore.exe" driver = webdriver.Ie(executable_path=driver_path, options=options, service_log_path='./Log/iedriver.log') elif self.browser == 'firefox': driver_path = "C:\\DevTools\\webdriver\\geckodriver_0.24.0.exe" driver = webdriver.Firefox( executable_path=driver_path, service_log_path='./Log/geckodriver.log') elif self.browser == 'chrome': # https://chromedriver.chromium.org/downloads/version-selection # PROD driver_path = "C:\\DevTools\\webdriver\\chromedriver_76.0.3809.126.exe" os.environ["webdriver.chrome.driver"] = driver_path options = Options() options.binary_location = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" driver = webdriver.Chrome( executable_path=driver_path, options=options, service_log_path='./Log/chromedriver.log') # DEV # driver_path = "C:\\DevTools\\webdriver\\chromedriver_77.0.3865.40.exe" # os.environ["webdriver.chrome.driver"] = driver_path # options = Options() # options.binary_location = "C:\\Program Files (x86)\\Google\\Chrome Dev\\Application\\chrome.exe" # driver = webdriver.Chrome(executable_path=driver_path, options=options, service_log_path='./Log/chromedriver.log') else: driver_path = "C:\\DevTools\\webdriver\\geckodriver_0.24.0.exe" driver = webdriver.Firefox( executable_path=driver_path, service_log_path='./Log/geckodriver.log') driver.implicitly_wait(3) driver.maximize_window() driver.get(baseURL) return driver
def __init__(self, v_bShow=False, v_WorkingPath='', v_UseCookies=False, v_Engine='Chrome', v_EngineDriver=None): LOG_FORMAT = ('%(levelname) -5s %(asctime)s %(name) -20s %(funcName) ' '-25s %(lineno) -5d: %(message)s') logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) self.StepTimeout = 15 self.WaitTimeout = 2 self.CookiesFile = '' self.UseCookies = v_UseCookies self.Engine = v_Engine self.EngineDriver = v_EngineDriver self.EngineDriverPath = '' if (v_WorkingPath != ''): LOGGER.info('WorkingPath: ' + os.path.realpath(v_WorkingPath)) if (self.Engine == 'IE'): self.CookiesFile = os.path.realpath( v_WorkingPath) + '\\cookies.pkl' else: self.CookiesFile = os.path.realpath( v_WorkingPath) + '/cookies.pkl' if (self.Engine == 'Chrome'): self.EngineDriver = '/usr/local/sbin/chromedriver' opts = ChOptions() opts.add_argument("binary_location = '/usr/bin/'") elif (self.Engine == 'IE'): opts = IeOptions() opts.add_argument( "binary_location = 'C:\\Program Files (x86)\\Internet Explorer'" ) elif (self.Engine == 'Firefox'): self.EngineDriver = '/usr/local/sbin/geckodriver' self.EngineDriver = '/usr/local/sbin' opts = GkOptions() opts.add_argument("binary_location = '/usr/bin/'") LOGGER.info('Engine: ' + self.Engine) LOGGER.info('EngineDriver: ' + self.EngineDriver) self.EngineDriverPath = os.path.dirname( os.path.abspath(self.EngineDriver)) sys.path.insert(0, self.EngineDriverPath) opts.add_argument("--start-maximized") opts.add_argument("--enable-automation") opts.add_argument("--log-level=3") opts.add_argument("--silent") opts.add_argument("--disable-infobars") opts.add_argument("--disable-dev-shm-usage") opts.add_argument("--disable-browser-side-navigation") opts.add_argument("--disable-gpu") opts.add_argument("--no-sandbox") opts.add_argument("--no-zygote") if (not v_bShow): LOGGER.info('Headless Operation') opts.add_argument("--headless") opts.add_argument("--disable-setuid-sandbox") if (self.Engine == 'Chrome'): self.Browser = ChWebBrowser(self.EngineDriver, options=opts) elif (self.Engine == 'IE'): self.Browser = IeWebBrowser(self.EngineDriver, options=opts) elif (self.Engine == 'Firefox'): self.Browser = GkWebBrowser(self.EngineDriver, options=opts) if (self.UseCookies): try: if ((self.CookiesFile != '') and (os.path.isfile(self.CookiesFile))): for cookie in pickle.load(open(self.CookiesFile, "rb")): self.Browser.add_cookie(cookie) LOGGER.info('Cookies Loaded') except Exception as Exc: LOGGER.info('Could Not Load Cookies ' + self.CookiesFile + ' - (' + str(Exc).strip() + ')') self.Browser.set_window_size(1920, 1080) self.Browser.set_window_position(0, 0)
def assemble_driver(self): # 若是谷歌驱动 if ConfigReader().read("project")["driver"].lower() == "chrome": # chrome option chrome_options = ChromeOptions() # 服务端 root 用户不能直接运行 chrome,添加此参数可以运行 chrome_options.add_argument('--no-sandbox') # # 下面参数可自行选择 # chrome_options.add_argument('--user-data-dir') # chrome_options.add_argument('--dns-prefetch-disable') # chrome_options.add_argument('--lang=en-US') # chrome_options.add_argument('--disable-setuid-sandbox') # chrome_options.add_argument('--disable-gpu') # 驱动路径 executable_path = os.path.abspath( os.path.dirname(__file__) )[:os.path.abspath(os.path.dirname(__file__) ).find("python-ui-auto-test") + len("python-ui-auto-test")] + "/ui-test" + ConfigReader().read( "driver")["chrome_driver_path"] # 如果读取不到 remote_ip 或者 remote_port 就不用远端浏览器 if ConfigReader().read( "project")["remote_ip"] == "" or ConfigReader().read( "project")["remote_port"] == "": self.driver = webdriver.Chrome(executable_path=executable_path, chrome_options=chrome_options) # 使用远端浏览器 else: url = "http://" + ConfigReader().read( "project")["remote_ip"] + ":" + ConfigReader().read( "project")["remote_port"] + "/wd/hub" self.driver = RemoteWebDriver(command_executor=url, options=chrome_options) # 若是火狐驱动 elif ConfigReader().read("project")["driver"].lower() == "firefox": # firefox option firefox_options = FirefoxOptions() # 服务端 root 用户不能直接运行 chrome,添加此参数可以运行 firefox_options.add_argument('--no-sandbox') # 驱动路径 executable_path = os.path.abspath( os.path.dirname(__file__) )[:os.path.abspath(os.path.dirname(__file__) ).find("python-ui-auto-test") + len("python-ui-auto-test")] + "/ui-test" + ConfigReader().read( "driver")["firefox_driver_path"] # 获取驱动自己产出日志路径 log_path = os.path.abspath( os.path.dirname(__file__) )[:os.path.abspath(os.path.dirname(__file__) ).find("python-ui-auto-test") + len("python-ui-auto-test")] + "/ui-test" + ConfigReader().read( "log")["logfile_path"] self.driver = webdriver.Firefox(executable_path=executable_path, log_path=log_path + "geckodriver.log", firefox_options=firefox_options) # 若是 IE 驱动 elif ConfigReader().read("project")["driver"].lower() == "ie": # ie option ie_options = IeOptions() # 服务端 root 用户不能直接运行 chrome,添加此参数可以运行 ie_options.add_argument('--no-sandbox') # 驱动路径 executable_path = os.path.abspath( os.path.dirname(__file__) )[:os.path.abspath(os.path.dirname(__file__) ).find("python-ui-auto-test") + len("python-ui-auto-test")] + "/ui-test" + ConfigReader().read( "driver")["ie_driver_path"] self.driver = webdriver.Ie(executable_path=executable_path, ie_options=ie_options) # 若是 Edge 驱动 elif ConfigReader().read("project")["driver"].lower() == "edge": executable_path = os.path.abspath( os.path.dirname(__file__) )[:os.path.abspath(os.path.dirname(__file__) ).find("python-ui-auto-test") + len("python-ui-auto-test")] + "/ui-test" + ConfigReader().read( "driver")["edge_driver_path"] self.driver = webdriver.Edge(executable_path=executable_path) # 若是欧朋驱动 elif ConfigReader().read("project")["driver"].lower() == "opera": executable_path = os.path.abspath( os.path.dirname(__file__) )[:os.path.abspath(os.path.dirname(__file__) ).find("python-ui-auto-test") + len("python-ui-auto-test")] + "/ui-test" + ConfigReader().read( "driver")["opera_driver_path"] self.driver = webdriver.Opera(executable_path=executable_path) # 若是 Safari 驱动 elif ConfigReader().read("project")["driver"].lower() == "safari": executable_path = os.path.abspath( os.path.dirname(__file__) )[:os.path.abspath(os.path.dirname(__file__) ).find("python-ui-auto-test") + len("python-ui-auto-test")] + "/ui-test" + ConfigReader().read( "driver")["safari_driver_path"] self.driver = webdriver.Safari(executable_path=executable_path) # 不支持的浏览器类型 else: self.driver = None raise RuntimeError("配置文件中配置了不支持的浏览器类型!请修改浏览器类型!")
def launch( name: str = "chrome", executable_path: str = None, grid_url: str = None, headless: bool = False, sandbox: bool = False, window_size: str = "1366x768", incognito: bool = False, infobars: bool = False, **kwargs, ): def get_options(options: Union[ChromeOptions, FirefoxOptions, IeOptions]): if not headless: options.add_argument("--headless") if not sandbox: options.add_argument("--no-sandbox") if window_size: options.add_argument(f"--window-size={window_size}") if not incognito: options.add_argument("--incognito") if not infobars: options.add_argument("--disable-infobars") return options if name == BrowserType.CHROME.value: chrome_options = get_options(ChromeOptions()) if not executable_path: executable_path = ChromeDriverManager().install() if grid_url: return webdriver.Remote( command_executor=grid_url, desired_capabilities=DesiredCapabilities.CHROME.copy(), options=chrome_options, **kwargs, ) return webdriver.Chrome(executable_path, options=chrome_options, **kwargs) elif name == BrowserType.FIREFOX.value: firefox_options = get_options(FirefoxOptions()) if not executable_path: executable_path = GeckoDriverManager().install() if grid_url: return webdriver.Remote( command_executor=grid_url, desired_capabilities=DesiredCapabilities.FIREFOX.copy(), options=firefox_options, **kwargs, ) return webdriver.Firefox(executable_path, options=firefox_options, **kwargs) elif name == BrowserType.IE.value: ie_options = get_options(IeOptions()) if not executable_path: executable_path = IEDriverManager().install() if grid_url: ca = DesiredCapabilities.INTERNETEXPLORER.copy() return webdriver.Remote( command_executor=grid_url, desired_capabilities=ca, options=ie_options, **kwargs, ) return webdriver.Ie(executable_path, options=ie_options, **kwargs)
def __init__(self, arguments): self.options = IeOptions() for argument in arguments: self.options.add_argument(argument)