selenium+Python 第一篇:为Browser对象封装关键字

本文详细介绍了如何使用Selenium进行自动化测试,包括打开浏览器、切换浏览器、获取页面源代码、验证页面元素等关键操作。同时,文章还讨论了设置Selenium的等待时间和隐式等待,以及如何管理多个浏览器会话。
摘要由CSDN通过智能技术生成

open_browser

    def open_browser(
        self,
        url: Optional[str] = None,
        browser: str = "firefox",
        alias: Optional[str] = None,
        remote_url: Union[bool, str] = False,
        desired_capabilities: Union[dict, None, str] = None,
        ff_profile_dir: Union[FirefoxProfile, str, None] = None,
        options: Any = None,
        service_log_path: Optional[str] = None,
        executable_path: Optional[str] = None,
    ) -> str:
        index = self.drivers.get_index(alias)
        if index:
            self.info(f"Using existing browser from index {index}.")
            self.switch_browser(alias)
            if url:
                self.go_to(url)
            return index
        return self._make_new_browser(
            url,
            browser,
            alias,
            remote_url,
            desired_capabilities,
            ff_profile_dir,
            options,
            service_log_path,
            executable_path,
        )
 def _make_new_browser(
        self,
        url=None,
        browser="firefox",
        alias=None,
        remote_url=False,
        desired_capabilities=None,
        ff_profile_dir=None,
        options=None,
        service_log_path=None,
        executable_path=None,
    ):
        if remote_url:
            self.info(
                f"Opening browser '{browser}' to base url '{url}' through "
                f"remote server at '{remote_url}'."
            )
        else:
            self.info(f"Opening browser '{browser}' to base url '{url}'.")
        driver = self._make_driver(
            browser,
            desired_capabilities,
            ff_profile_dir,
            remote_url,
            options,
            service_log_path,
            executable_path,
        )
        driver = self._wrap_event_firing_webdriver(driver)
        index = self.ctx.register_driver(driver, alias)
        if url:
            try:
                driver.get(url)
            except Exception:
                self.debug(
                    f"Opened browser with session id {driver.session_id} but failed to open url '{url}'."
                )
                raise
        self.debug(f"Opened browser with session id {driver.session_id}.")
        return index
 def _make_driver(
        self,
        browser,
        desired_capabilities=None,
        profile_dir=None,
        remote=None,
        options=None,
        service_log_path=None,
        executable_path=None,
    ):
        driver = self._webdriver_creator.create_driver(
            browser=browser,
            desired_capabilities=desired_capabilities,
            remote_url=remote,
            profile_dir=profile_dir,
            options=options,
            service_log_path=service_log_path,
            executable_path=executable_path,
        )
        driver.set_script_timeout(self.ctx.timeout)
        driver.implicitly_wait(self.ctx.implicit_wait)
        if self.ctx.speed:
            self._monkey_patch_speed(driver)
        return driver

create_driver

    def create_webdriver(
        self, driver_name: str, alias: Optional[str] = None, kwargs={}, **init_kwargs
    ) -> str:
        if not isinstance(kwargs, dict):
            raise RuntimeError("kwargs must be a dictionary.")
        for arg_name in kwargs:
            if arg_name in init_kwargs:
                raise RuntimeError(f"Got multiple values for argument '{arg_name}'.")
            init_kwargs[arg_name] = kwargs[arg_name]
        driver_name = driver_name.strip()
        try:
            creation_func = getattr(webdriver, driver_name)
        except AttributeError:
            raise RuntimeError(f"'{driver_name}' is not a valid WebDriver name.")
        self.info(f"Creating an instance of the {driver_name} WebDriver.")
        driver = creation_func(**init_kwargs)
        self.debug(
            f"Created {driver_name} WebDriver instance with session id {driver.session_id}."
        )
        driver = self._wrap_event_firing_webdriver(driver)
        return self.ctx.register_driver(driver, alias)

close_allbrowser

    def close_all_browsers(self):
        """Closes all open browsers and resets the browser cache.
        After this keyword, new indexes returned from `Open Browser` keyword
        are reset to 1.
        This keyword should be used in test or suite teardown to make sure
        all browsers are closed.
        """
        self.debug("Closing all browsers.")
        self.drivers.close_all()

 

switch_browser

 def switch_browser(self, index_or_alias: str):
        
        try:
            self.drivers.switch(index_or_alias)
        except RuntimeError:
            raise RuntimeError(
                f"No browser with index or alias '{index_or_alias}' found."
            )
        self.debug(
            f"Switched to browser with Selenium session id {self.driver.session_id}."
        )

get_browserid

    def get_browser_ids(self) -> List[str]:
        return self.drivers.active_driver_ids

get_browser_aliases

    def get_browser_aliases(self) -> List[str]:
        return self.drivers.active_aliases

get_session_id 

def get_session_id(self) -> str:
    """Returns the currently active browser session id.

    New in SeleniumLibrary 3.2
    """
    return self.driver.session_id

get_source


def get_source(self) -> str:
    """Returns the entire HTML source of the current page or frame."""
    return self.driver.page_source

get_title 

    def get_title(self) -> str:
        """Returns the title of the current page."""
        return self.driver.title

 get_location

 def get_location(self) -> str:
        """Returns the current browser window URL."""
        return self.driver.current_url

location_should_be 

    def location_should_be(self, url: str, message: Optional[str] = None):
        
        actual = self.get_location()
        if actual != url:
            if message is None:
                message = f"Location should have been '{url}' but " f"was '{actual}'."
            raise AssertionError(message)
        self.info(f"Current location is '{url}'.")

 location_should_contain

    def location_should_contain(self, expected: str, message: Optional[str] = None):
       
        actual = self.get_location()
        if expected not in actual:
            if message is None:
                message = (
                    f"Location should have contained '{expected}' but "
                    f"it was '{actual}'."
                )
            raise AssertionError(message)
        self.info(f"Current location contains '{expected}'.")

log_location 

    def log_location(self) -> str:
        """Logs and returns the current browser window URL."""
        url = self.get_location()
        self.info(url)
        return url

log_source 

def log_source(self, loglevel: str = "INFO") -> str:
    """Logs and returns the HTML source of the current page or frame.

    The ``loglevel`` argument defines the used log level. Valid log
    levels are ``WARN``, ``INFO`` (default), ``DEBUG``, ``TRACE``
    and ``NONE`` (no logging).
    """
    source = self.get_source()
    self.log(source, loglevel)
    return source

 log_title

    def log_title(self) -> str:
        """Logs and returns the title of the current page."""
        title = self.get_title()
        self.info(title)
        return title

title_should_be 

 def title_should_be(self, title: str, message: Optional[str] = None):
        """Verifies that the current page title equals ``title``.

        The ``message`` argument can be used to override the default error
        message.

        ``message`` argument is new in SeleniumLibrary 3.1.
        """
        actual = self.get_title()
        if actual != title:
            if message is None:
                message = f"Title should have been '{title}' but was '{actual}'."
            raise AssertionError(message)
        self.info(f"Page title is '{title}'.")

go_back 

    def go_back(self):
        """Simulates the user clicking the back button on their browser."""
        self.driver.back()

 go_to

    def go_to(self, url):
        """Navigates the current browser window to the provided ``url``."""
        self.info(f"Opening url '{url}'")
        self.driver.get(url)

reload_page 

    def reload_page(self):
        """Simulates user reloading page."""
        self.driver.refresh()

 get_selenium_speed

    def get_selenium_speed(self) -> str:
        """Gets the delay that is waited after each Selenium command.

        The value is returned as a human-readable string like ``1 second``.

        See the `Selenium Speed` section above for more information.
        """
        return secs_to_timestr(self.ctx.speed)

get_selenium_timeout 

    def get_selenium_timeout(self) -> str:
        """Gets the timeout that is used by various keywords.

        The value is returned as a human-readable string like ``1 second``.

        See the `Timeout` section above for more information.
        """
        return secs_to_timestr(self.ctx.timeout)

get_selenium_implicit_wait 

    def get_selenium_implicit_wait(self) -> str:
        """Gets the implicit wait value used by Selenium.

        The value is returned as a human-readable string like ``1 second``.

        See the `Implicit wait` section above for more information.
        """
        return secs_to_timestr(self.ctx.implicit_wait)

set_selenium_speed 

    def set_selenium_speed(self, value: timedelta) -> str:
  
        old_speed = self.get_selenium_speed()
        self.ctx.speed = _convert_timeout(value)
        for driver in self.drivers.active_drivers:
            self._monkey_patch_speed(driver)
        return old_speed

set_selenium_timeout

    def set_selenium_timeout(self, value: timedelta) -> str:
        
        old_timeout = self.get_selenium_timeout()
        self.ctx.timeout = _convert_timeout(value)
        for driver in self.drivers.active_drivers:
            driver.set_script_timeout(self.ctx.timeout)
        return old_timeout

 set_selenium_implicit_wait

    def set_selenium_implicit_wait(self, value: timedelta) -> str:
        """Sets the implicit wait value used by Selenium.

        The value can be given as a number that is considered to be
        seconds or as a human-readable string like ``1 second``.
        The previous value is returned and can be used to restore
        the original value later if needed.

        This keyword sets the implicit wait for all opened browsers.
        Use `Set Browser Implicit Wait` to set it only to the current
        browser.

        See the `Implicit wait` section above for more information.

        Example:
        | ${orig wait} = | `Set Selenium Implicit Wait` | 10 seconds |
        | `Perform AJAX call that is slow` |
        | `Set Selenium Implicit Wait` | ${orig wait} |
        """
        old_wait = self.get_selenium_implicit_wait()
        self.ctx.implicit_wait = _convert_timeout(value)
        for driver in self.drivers.active_drivers:
            driver.implicitly_wait(self.ctx.implicit_wait)
        return old_wait

    

 set_browser_implicit_wait

@keyword
    def set_browser_implicit_wait(self, value: timedelta):
        """Sets the implicit wait value used by Selenium.

        Same as `Set Selenium Implicit Wait` but only affects the current
        browser.
        """
        self.driver.implicitly_wait(_convert_timeout(value))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全栈开发与测试

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值