def driver(config): driver = None if config['selenoid'] is not None: capabilities = { "browserName": "chrome", "browserVersion": "80.0", "selenoid:options": { "enableVNC": False, "enableVideo": False } } selenoid_url = 'http://' + config['selenoid'] + '/wd/hub' options = ChromeOptions() driver = webdriver.Remote(command_executor=selenoid_url, options=options, desired_capabilities=capabilities) driver.file_detector = LocalFileDetector() else: options = ChromeOptions() driver = webdriver.Chrome( ChromeDriverManager().install(), options=options, desired_capabilities=DesiredCapabilities().CHROME) driver.maximize_window() driver.get(config['url']) yield driver driver.quit()
def send_keys(loc, text): """Sends the supplied keys to an element. Handles the file upload fields on background. If it detects the element is and input of type file, it uses the LocalFileDetector so the file gets transferred properly. Otherwise it takes care of having UselessFileDetector. Args: loc: A locator, expects either a string, WebElement, tuple. text: The text to inject into the element. """ if text is not None: file_intercept = False # If the element is input type file, we will need to use the file detector if tag(loc) == 'input': type_attr = get_attribute(loc, 'type') if type_attr and type_attr.strip() == 'file': file_intercept = True try: if file_intercept: # If we detected a file upload field, let's use the file detector. browser().file_detector = LocalFileDetector() move_to_element(loc).send_keys(text) finally: # Always the UselessFileDetector for all other kinds of fields, so do not leave # the LocalFileDetector there. if file_intercept: browser().file_detector = UselessFileDetector() wait_for_ajax()
def __init__(self, options=None, capabilities=None, service_url=None, session_id=None): if options == None: self.service = False else: self.service = True self.address = options[0] self.who = options[1] # super(Chrome_Remote, self).__init__(port=port) if service_url is None and session_id is None: raise NameError if capabilities is None: capabilities = DesiredCapabilities.CHROME.copy() self.capabilities = dict(capabilities) self.w3c = True executor = ChromeRemoteConnection(remote_server_addr=service_url) self.session_id = session_id self.command_executor = executor self.command_executor.w3c = self.w3c if type(self.command_executor) is bytes or isinstance( self.command_executor, str): self.command_executor = RemoteConnection(self.command_executor, keep_alive=True) self._is_remote = True self.error_handler = ErrorHandler() self._switch_to = SwitchTo(self) self._mobile = Mobile(self) self.file_detector = LocalFileDetector()
def setUp(self): self.selenium.file_detector = LocalFileDetector() session = localstack_client.session.Session(region_name="us-west-1") self.s3 = session.resource("s3") self.bucket = self.s3.Bucket(settings.AWS_STORAGE_BUCKET_NAME) # Delete all current files for obj in self.bucket.objects.all(): obj.delete() super().setUp()
def test_sandbox(live_server, logged_in_browser): """ Test adding, modifying and deleting a sandbox record """ browser = logged_in_browser browser.file_detector = LocalFileDetector() # Go to sandbox sandbox_url = flask.url_for('hepdata_records.sandbox', _external=True) browser.get(sandbox_url) e2e_assert_url(browser, 'hepdata_records.sandbox') # Check there are no past sandbox submissions assert browser.find_element_by_id('past_submissions') \ .find_elements_by_xpath(".//*") == [] # Try uploading a file upload = browser.find_element_by_id('root_file_upload') ActionChains(browser).move_to_element(upload).perform() upload.send_keys(os.path.abspath("tests/test_data/TestHEPSubmission.zip")) browser.find_element_by_class_name('btn-primary').click() # Should redirect to record page with confirmation message WebDriverWait(browser, 15).until( EC.url_matches(f'{sandbox_url}/\\d+') ) alert = browser.find_element_by_class_name('alert-info') assert alert.text == "File saved. You will receive an email when the file has been processed." # Record should have been processed immediately by test celery runner # so we can check its contents _check_record_common(browser) # Go back to the sandbox browser.get(sandbox_url) # Check that past submissions column now has a child past_submissions_div = browser.find_element_by_id('past_submissions') assert len(past_submissions_div.find_elements_by_class_name('col-md-10')) == 1 # Delete the sandbox record past_submissions_div.find_element_by_class_name('delete_button').click() delete_modal = browser.find_element_by_id('deleteWidget') WebDriverWait(browser, 10).until( EC.visibility_of(delete_modal) ) delete_modal.find_element_by_class_name('confirm-delete').click() WebDriverWait(browser, 10).until( EC.text_to_be_present_in_element((By.ID, 'deleteDialogLabel'), 'Submission Deleted') ) # Refresh sandbox page (to avoid waiting) browser.get(sandbox_url) # Check there are no past sandbox submissions assert browser.find_element_by_id('past_submissions') \ .find_elements_by_xpath(".//*") == []
def attach_file(self, element, file_name): log_step(f"Attach file {file_name}") file_path = session.data_dir.joinpath(file_name) if not Path.exists(file_path): raise IOError(f"File does not exist: {file_path}") self.get_driver().file_detector = LocalFileDetector() self.fill_field(element, str(file_path))
def do_import(self, file_content=None, file_path=None): """ Imports the file. Currently the only type supported is 'safenet'. Either xml_content (string) or file_path (string) has to be present. If file_content is not None and there is no path then file_content is written to a temporary file that is used for the import. :param file_content: xml string with Token import details :param file_path: the file path of provided xml token file :raises TokenImportError if the import failed """ if (not file_content and not file_path): raise Exception("""Wrong test implementation. TokenImport.do_import needs file_content or file_path! """) if file_content: # Create the temp xml file with the given file_content. tf = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".xml") tf.write(file_content) tf.close() self.file_path = tf.name else: # Use the provided xml token file. self.file_path = file_path # We need to make the file available in the selenium # docker container (Where the browser interaction is done). self.driver.file_detector = LocalFileDetector() # On firefox the lineedit is not cleared after dialog re-open # So we have to do this explicitly # Otherwise the token file to load will be added and # LinOTP ends up in an undefined state. self.driver.find_element_by_xpath(self.file_name_lineedit).clear() # Send the filename to the token file lineedit in the dialog. self.driver.find_element_by_xpath(self.file_name_lineedit).send_keys( self.file_path) self.driver.find_element_by_id(self.load_button_id).click() self.manage.wait_for_waiting_finished() # delete the temp file if necessary if (file_content): os.unlink(self.file_path) # Check the alert boxes on the top of the LinOTP UI info = self.manage.alert_box_handler.last_line if info.type != 'info' or not info.text.startswith( 'Token import result:'): raise TokenImportError('Import failure:{}'.format(info))
def main(): logging.getLogger().setLevel(logging.INFO) # Setup Selenium web driver parser = get_arg_parser() args = parser.parse_args() if args.browser == "docker": driver = webdriver.Remote( command_executor="http://127.0.0.1:4444/wd/hub", desired_capabilities=DesiredCapabilities.FIREFOX, ) elif args.browser == "firefox": firefox_profile = webdriver.FirefoxProfile() firefox_profile.set_preference("intl.accept_languages", "en-us") firefox_profile.update_preferences() driver = webdriver.Firefox(firefox_profile) elif args.browser == "chrome": driver = webdriver.Chrome() else: raise ArgumentError(message="Unknown driver.") driver.set_window_size(1920, 1080) login_using_cookie_file(driver, cookie_file=args.login_cookies) driver.get("https://www.youtube.com") assert "YouTube" in driver.title try: confirm_logged_in(driver) driver.get("https://studio.youtube.com") assert "Channel dashboard" in driver.title driver.file_detector = LocalFileDetector() upload_file( driver, video_path=args.video_path, title=args.title, thumbnail_path=args.thumbnail, description=args.description, game=args.game, kids=args.kids, upload_time=args.upload_time, ) except: driver.close() raise
def __init__(self, manage_ui: ManageUi): """Constructor: create a new LicenseImport class remarks: using LocalFileDetector: we need to make the file available in the selenium docker container. Therefore we require to use the LocalFileDetector :param manage_ui: The base manage class for the ui elements """ # ----------------------------------------------------------------- -- # init the parent class ManageDialog.__init__(self, manage_ui) self.manage_ui = manage_ui # ----------------------------------------------------------------- -- # to support selenium remote we need to setup the LocalFileDetector self.driver.file_detector = LocalFileDetector() # ----------------------------------------------------------------- -- # open the manage interface - do the cleanup if something was left open self.manage.open_manage() self.manage_ui.close_all_dialogs() self.manage_ui.close_all_menus() # ----------------------------------------------------------------- -- # navigate from the help menu to the upload dialog self.manage.find_by_css(self.manage.MENU_LINOTP_HELP_CSS).click() self.driver.find_element(By.ID, self.menu_item_id) for butten_id in self.menu_dialogs: self.driver.find_element(By.ID, butten_id).click()
def __init__(self, capabilities=None, service_url=None, session_id=None): if service_url is None and session_id is None: raise NameError if capabilities is None: capabilities = DesiredCapabilities.FIREFOX.copy() self.capabilities = dict(capabilities) self.w3c = True executor = ChromeRemoteConnection(remote_server_addr=service_url) self.session_id = session_id self.command_executor = executor self.command_executor.w3c = self.w3c if type(self.command_executor) is bytes or isinstance(self.command_executor, str): self.command_executor = RemoteConnection(self.command_executor, keep_alive=True) self._is_remote = True self.error_handler = ErrorHandler() self._switch_to = SwitchTo(self) self._mobile = Mobile(self) self.file_detector = LocalFileDetector()
def create_driver_instance(browser_name: str): """Create a new web driver instance. :param browser_name: Browser name (chrome|firefox) :return: New web driver instance """ if browser_name.lower() == 'chrome': chrome_opt = __create_chrome_options() return webdriver.Chrome(executable_path=__CHROME_PATH, chrome_options=chrome_opt) elif browser_name.lower() == 'firefox': firefox_driver = webdriver.Firefox(executable_path=__FIREFOX_PATH) firefox_driver.maximize_window() return firefox_driver elif browser_name.lower() == 'chrome-remote': from selenium.webdriver.remote.file_detector import LocalFileDetector driver = webdriver.Remote(command_executor='url') driver.file_detector = LocalFileDetector() raise NotImplemented('Not working...') else: raise ValueError(f'Invalid browser selected: {browser_name}!')
def send_keys(self, text: str, locator: LocatorAlias, *args, **kwargs) -> None: """Sends keys to the element. Detects the file inputs automatically. Args: text: Text to be inserted to the element. *args: See :py:meth:`elements` **kwargs: See :py:meth:`elements` """ text = str(text) or "" file_intercept = False # If the element is input type file, we will need to use the file detector if self.tag(locator, *args, **kwargs) == "input": type_attr = self.get_attribute("type", locator, *args, **kwargs) if type_attr and type_attr.strip() == "file": file_intercept = True try: if file_intercept: # If we detected a file upload field, let's use the file detector. self.selenium.file_detector = LocalFileDetector() el = self.move_to_element(locator, *args, **kwargs) self.plugin.before_keyboard_input(el, text) self.logger.debug("send_keys %r to %r", text, locator) result = el.send_keys(text) if Keys.ENTER not in text: try: self.plugin.after_keyboard_input(el, text) except StaleElementReferenceException: pass else: self.logger.info( "skipped the after_keyboard_input call due to %r containing ENTER.", text, ) return result finally: # Always the UselessFileDetector for all other kinds of fields, so do not leave # the LocalFileDetector there. if file_intercept: self.selenium.file_detector = UselessFileDetector()
class SelLibLocalFileDetector(FileDetector): def __init__(self): self.selenium_file_detector = LocalFileDetector() def is_local_file(self, *keys): if self.choose_file(): return self.selenium_file_detector.is_local_file(*keys) return None def choose_file(self): try: sl = self._get_sl() except Exception: sl = None if sl and sl._running_keyword == 'choose_file': return True return False def _get_sl(self): libraries = BuiltIn().get_library_instance(all=True) for library in libraries: if isinstance(libraries[library], SeleniumLibrary.SeleniumLibrary): return libraries[library]
def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=None, browser_profile=None, proxy=None, keep_alive=False, file_detector=None, session_id=None, w3c=True): """ Create a new driver that will issue commands using the wire protocol. :Args: - command_executor - Either a string representing URL of the remote server or a custom remote_connection.RemoteConnection object. Defaults to 'http://127.0.0.1:4444/wd/hub'. - desired_capabilities - A dictionary of capabilities to request when starting the browser session. Required parameter. - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested. Optional. - proxy - A selenium.webdriver.common.proxy.Proxy object. The browser session will be started with given proxy settings, if possible. Optional. - keep_alive - Whether to configure remote_connection.RemoteConnection to use HTTP keep-alive. Defaults to False. - file_detector - Pass custom file detector object during instantiation. If None, then default LocalFileDetector() will be used. """ if desired_capabilities is None: raise WebDriverException("Desired Capabilities can't be None") if not isinstance(desired_capabilities, dict): raise WebDriverException( "Desired Capabilities must be a dictionary") if proxy is not None: warnings.warn("Please use FirefoxOptions to set proxy", DeprecationWarning) proxy.add_to_capabilities(desired_capabilities) if (desired_capabilities["browserName"] == 'firefox'): command_executor = FirefoxRemoteConnection( remote_server_addr=command_executor) self.command_executor = command_executor if type(self.command_executor) is bytes or isinstance( self.command_executor, str): self.command_executor = RemoteConnection(command_executor, keep_alive=keep_alive) self._is_remote = True self.session_id = session_id # added self.capabilities = dict(desired_capabilities) self.error_handler = ErrorHandler() self.start_client() if browser_profile is not None: warnings.warn("Please use FirefoxOptions to set browser profile", DeprecationWarning) if session_id: if desired_capabilities["browserName"] != "firefox": self.connect_to_session(desired_capabilities) # added else: pass self.w3c = w3c # modified by zhengchun else: self.start_session(desired_capabilities, browser_profile) self._switch_to = SwitchTo(self) self._mobile = Mobile(self) self.file_detector = file_detector or LocalFileDetector()
def test_record_update(live_server, logged_in_browser): """ Test making changes to a record. """ browser = logged_in_browser browser.file_detector = LocalFileDetector() inspire_id = '1283842' # Check there's just 1 version of our submission submissions = HEPSubmission.query.filter_by( inspire_id=inspire_id).all() assert len(submissions) == 1 assert submissions[0].version == 1 # Go to existing (default) record and create a new version record_url = flask.url_for( 'hepdata_records.get_metadata_by_alternative_id', recid=f'ins{inspire_id}', _external=True) browser.get(record_url) browser.find_element_by_css_selector( "button.btn-danger[data-target='#reviseSubmission']").click() revise_submission_dialog = browser.find_element_by_id('reviseSubmission') WebDriverWait(browser, 10).until( EC.visibility_of(revise_submission_dialog) ) # Check for warning about a new version assert "This submission is already finished." in \ revise_submission_dialog.find_element_by_id('revise-confirm').text # Click "Revise Submission" button and wait for response revise_submission_dialog.find_element_by_css_selector("#revise-confirm button[type='submit']").click() revise_success = browser.find_element_by_id('revise-success') WebDriverWait(browser, 10).until( EC.visibility_of(revise_success) ) assert revise_success.find_element_by_tag_name('p').text \ .startswith("Version 2 created.\nThis window will close in ") # Refresh record page (to avoid waiting) browser.get(record_url) # Should now be 2 versions of our submission submissions = HEPSubmission.query \ .filter_by(inspire_id=inspire_id) \ .order_by(HEPSubmission.created).all() assert len(submissions) == 2 assert submissions[0].version == 1 assert submissions[0].overall_status == 'finished' assert submissions[1].version == 2 assert submissions[1].overall_status == 'todo' # Upload a new file upload = browser.find_element_by_id('root_file_upload') ActionChains(browser).move_to_element(upload).perform() upload.send_keys(os.path.abspath("tests/test_data/TestHEPSubmission.zip")) browser.find_element_by_css_selector('form[name=upload-form] input[type=submit]').click() # Wait for page reload WebDriverWait(browser, 15).until( EC.staleness_of(upload) ) alert = browser.find_element_by_class_name('alert-info') assert alert.text == "File saved. You will receive an email when the file has been processed." # Run common checks _check_record_common(browser) # Add some reviews # Check initial status of Table 1 is "ToDo" table1_summary = browser.find_element_by_id('table-list') \ .find_element_by_class_name('Table1') table1_id = table1_summary.get_attribute('id') table1_status = table1_summary.find_element_by_id(f'{table1_id}-status') assert "todo" in table1_status.get_attribute('class') # Change review status browser.find_element_by_id('reviewer-button').click() reviews_view = browser.find_element_by_class_name('reviews-view') WebDriverWait(browser, 10).until( EC.visibility_of(reviews_view) ) reviews_view.find_element_by_id('attention-option').click() if "attention" not in table1_status.get_attribute('class'): WebDriverWait(browser, 10).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, f"span[id='{table1_id}-status'][class*='attention']") ) ) assert "attention" in table1_status.get_attribute('class') # Send a message message_box = reviews_view.find_element_by_id('message') ActionChains(browser).move_to_element(message_box).perform() message_box.send_keys("This needs to change!") reviews_view.find_element_by_id('save_no_email').click() # Wait until message appears message = WebDriverWait(browser, 10).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, '#review_messages .message-content') ) ) assert "This needs to change!" in message.text assert "*****@*****.**" in message.find_element_by_class_name('reviewer').text # Close review pane browser.find_element_by_id('reviewer-button').click() # Switch to Table 2 and change review status table2_summary = browser.find_element_by_id('table-list') \ .find_element_by_class_name('Table2') table2_summary.click() table2_id = table2_summary.get_attribute('id') table2_status = table2_summary.find_element_by_id(f'{table2_id}-status') assert "todo" in table2_status.get_attribute('class') # Change review status browser.find_element_by_id('reviewer-button').click() reviews_view = browser.find_element_by_class_name('reviews-view') WebDriverWait(browser, 10).until( EC.visibility_of(reviews_view) ) reviews_view.find_element_by_id('passed-option').click() if "passed" not in table2_status.get_attribute('class'): WebDriverWait(browser, 10).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, f"span[id='{table2_id}-status'][class*='passed']") ) ) assert "passed" in table2_status.get_attribute('class') # Check "Notify Coordinator" is hidden assert not browser.find_element_by_id('notify-coordinator-btn').is_displayed() # Click "Approve All" browser.find_element_by_id('approve-all-btn').click() approve_all_modal = browser.find_element_by_id('approveAllTables') WebDriverWait(browser, 10).until( EC.visibility_of(approve_all_modal) ) approve_all_modal.find_element_by_id('confirmApproveAll').click() approve_all_modal.find_element_by_css_selector('button[type=submit]').click() # Wait for page reload WebDriverWait(browser, 10).until( EC.staleness_of(approve_all_modal) ) # Check all statuses are now 'passed' review_statuses = browser.find_element_by_id('table-list') \ .find_elements_by_class_name('review-status') for element in review_statuses: assert "passed" in element.get_attribute('class') # Check that "Approve all" button is not visible and "Notify Coordinator" # is now visible assert not browser.find_element_by_id('approve-all-btn').is_displayed() assert browser.find_element_by_id('notify-coordinator-btn').is_displayed() # Delete the new version # Open admin slider browser.find_element_by_id('admin-button').click() admin_view = browser.find_element_by_class_name('admin-view') WebDriverWait(browser, 10).until( EC.visibility_of(admin_view) ) # Click "Delete" admin_view.find_element_by_css_selector( "button.btn-danger[data-target='#deleteWidget']" ).click() # Wait for modal to load delete_widget = browser.find_element_by_id('deleteWidget') WebDriverWait(browser, 10).until( EC.visibility_of(delete_widget) ) assert delete_widget.find_element_by_css_selector('#delete-confirm p').text \ .startswith("Are you sure you want to delete the latest version of this submission?") # Click "Delete now" delete_widget.find_element_by_class_name('confirm-delete').click() # Wait for confirmation of deletion WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.ID, 'delete-success')) ) assert 'Submission deleted' in \ delete_widget.find_element_by_css_selector('#delete-success p').text # Should now only be 1 version of our submission submissions = HEPSubmission.query \ .filter_by(inspire_id=inspire_id).all() assert len(submissions) == 1 assert submissions[0].version == 1 assert submissions[0].overall_status == 'finished'
def setUp(self): self.selenium.file_detector = LocalFileDetector() super().setUp()
def test_upload_page(setup): file_path = 'file_uploader/test_file.txt' page = UploadPage(setup) page.file_detector = LocalFileDetector() page.open('upload') assert page.upload(file_path) == 'test_file.txt'
def __init__(self, sess_id, svr_addr): super(WebDriver, self).__init__() self.command_executor = RemoteConnection(svr_addr, True) self.session_id = sess_id self.error_handler = ErrorHandler() self.file_detector = LocalFileDetector()
def _init_web_driver(self): """ 初始化web浏览器 :return: driver """ driver_version = self._conf.get('browser') distribute = self._conf.get('seleniumGrid') driver = '' # 分布式开关开时,远程驱动浏览器,分布式开关关时本地驱动浏览器 if not distribute.get('switch'): # 本地驱动chrome浏览器 if operator.contains(driver_version.lower(), 'chrome'): driver_path = self._driver_root_path + 'chrome' + os.sep + self._conf.get( 'webbrowser').get(driver_version) driver = webdriver.Chrome(executable_path=driver_path) # 本地驱动firefox浏览器 elif operator.contains(driver_version.lower(), 'firefox'): driver_path = self._driver_root_path + 'firefox' + os.sep + self._conf.get( 'webbrowser').get(driver_version) driver = webdriver.Firefox(executable_path=driver_path) # 本地驱动ie浏览器 elif operator.contains(driver_version.lower(), 'ie'): driver_path = self._driver_root_path + 'ie' + os.sep + self._conf.get( 'webbrowser').get(driver_version) driver = webdriver.Ie(executable_path=driver_path) # 本地驱动edge浏览器 elif operator.contains(driver_version.lower(), 'edge'): driver_path = self._driver_root_path + 'edge' + os.sep + self._conf.get( 'webbrowser').get(driver_version) driver = webdriver.Edge(executable_path=driver_path) else: raise self._logger.error('您选择的浏览器类型赞不支持') elif distribute.get('switch'): # 远程驱动chrome浏览器 if operator.contains(driver_version.lower(), 'chrome'): driver_path = '/opt/selenium/chromedriver-86.0.4240.22' chrome_desired = { "browserName": "chrome", "platform": "LINUX", "cssSelectorsEnabled": True, "javascriptEnabled": True, "binary": driver_path, } driver = webdriver.Remote( command_executor=distribute.get('hubUrl'), desired_capabilities=chrome_desired) # 远程驱动firefox浏览器,暂不支持 elif operator.contains(driver_version.lower(), 'firefox'): driver_path = self._driver_root_path + 'firefox' + os.sep + self._conf.get( 'webbrowser').get(driver_version) fox_desired = { "browserName": "firefox", "platform": "WINDOWS", "cssSelectorsEnabled": True, "javascriptEnabled": True, "firefox_binary": driver_path, } driver = webdriver.Remote( command_executor=distribute.get('hubUrl'), desired_capabilities=fox_desired) # 远程本地驱动ie浏览器 elif operator.contains(driver_version.lower(), 'ie'): driver_path = self._driver_root_path + 'ie' + os.sep + self._conf.get( 'webbrowser').get(driver_version) ie_desired = { "browserName": "internet explorer", "platform": "WINDOWS", "cssSelectorsEnabled": True, "javascriptEnabled": True, "binary": driver_path, } driver = webdriver.Remote( command_executor=distribute.get('hubUrl'), desired_capabilities=ie_desired) # 远程驱动edge浏览器,暂不支持 elif operator.contains(driver_version.lower(), 'edge'): driver_path = self._driver_root_path + 'edge' + os.sep + self._conf.get( 'webbrowser').get(driver_version) edge_desired = { "browserName": "MicrosoftEdge", "platform": "WINDOWS", "cssSelectorsEnabled": True, "javascriptEnabled": True, "binary": driver_path, } driver = webdriver.Remote( command_executor=distribute.get('hubUrl'), desired_capabilities=edge_desired) else: self._logger.error('您选择的浏览器类型赞不支持') driver.file_detector = LocalFileDetector() # 浏览器最大化 driver.maximize_window() # 项目名称 project = self._conf.get('project') # 项目url url = self._conf.get(project).get('url') # 输入地址到浏览器地址栏 driver.get(url=url) driver.implicitly_wait(self._conf.get(project).get('timeout')) return driver
def __init__(self): self.selenium_file_detector = LocalFileDetector()
from selenium import webdriver firefox_options = webdriver.FirefoxOptions() driver = webdriver.Remote(command_executor='http://www.example.com', options=firefox_options) driver.get("http://www.google.com") driver.quit() from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.set_capability("browserVersion", "67") chrome_options.set_capability("platformName", "Windows XP") driver = webdriver.Remote(command_executor='http://www.example.com', options=chrome_options) driver.get("http://www.google.com") driver.quit() from selenium.webdriver.remote.file_detector import LocalFileDetector driver.file_detector = LocalFileDetector() driver.get("http://sso.dev.saucelabs.com/test/guinea-file-upload") driver.find_element( By.ID, "myfile").send_keys("/Users/sso/the/local/path/to/darkbulb.jpg")