Пример #1
0
 def check_and_create_directories():
     print("Check and create directories")
     fs = FileSystem()
     directories = [
         config.PATH_TO_OUTPUT_DIR,
         fs.join_path(config.PATH_TO_OUTPUT_DIR),
     ]
     UtilityMethods.check_and_remove_directories(directories[0])
     UtilityMethods.check_and_create_directories(directories)
     return {"output": fs.absolute_path(directories[0])}
Пример #2
0
 def prepare_and_get_output_excel_path(path_to_destination_directory):
     fs = FileSystem()
     full_path_to_template = fs.absolute_path(
         config.PATH_TO_EXCEL_OUTPUT_TEMPLATE_FILE)
     file_name = fs.get_file_name(full_path_to_template)
     source_path = full_path_to_template
     destination_path = fs.join_path(path_to_destination_directory,
                                     file_name)
     fs.copy_file(destination=destination_path, source=source_path)
     return destination_path
Пример #3
0
def download_order_file(url: str, filename: str, download_path: str):
    print("___attemting to download order file___")
    try:
        browser = Browser.Browser()
        fileSystem = FileSystem()
        fileSystem.create_directory(download_path)
        browser.new_browser(downloadsPath=download_path)
        browser.new_context(acceptDownloads=True)
        browser.new_page()
        order_file_download = browser.download(url)
        orders_csv_filepath_origin = order_file_download.get("saveAs")
        orders_csv_filepath = download_path + filename
        fileSystem.wait_until_created(orders_csv_filepath_origin)
        fileSystem.copy_file(source=orders_csv_filepath_origin,
                             destination=orders_csv_filepath)
    except Exception as errorMessage:
        print("Unable to download order file: " + str(errorMessage))
    finally:
        browser.playwright.close()
    print("_____complete download____")
Пример #4
0
    def add_work_item_files(self, pattern):
        """Add all files that match given pattern to work item.

        Example:

        .. code-block:: robotframework

            Add work item files    %{ROBOT_ROOT}/generated/*.csv
            Save work item

        :param pattern: Path wildcard pattern
        """
        matches = FileSystem().find_files(pattern, include_dirs=False)

        paths = []
        for match in matches:
            path = self.add_work_item_file(match)
            paths.append(path)

        logging.info("Added %d file(s)", len(paths))
        return paths
Пример #5
0
def set_command():
    """Access Robocorp Vault in development enviroment"""
    click.secho("Use Robocorp Vault", fg="white", bold=True, underline=True)
    dev_account_exist = does_dev_access_account_exist()
    if dev_account_exist:
        click.echo("DEV access account already exists")
    else:
        ask_for_access_credentials()
    env_vars = check_for_environment_variables()
    workspace = click.prompt(
        "What is your workspace ID?",
        default=env_vars["RC_WORKSPACE_ID"],
        show_default=True,
    )

    # token_validity = click.prompt(
    #     "Access token validity time in minutes (max 1440 min = 24 hours)",
    #     default=1440,
    #     type=int,
    # )
    token_validity = 1440
    ret = run_command(
        f"rcc cloud authorize -a DEV -w {workspace} -m {token_validity}")
    if "Error:" in ret:
        output_and_exit(ret)
    ret = json.loads(ret)
    expiry_time = ret["when"] + timedelta(
        minutes=token_validity).total_seconds()

    json_exists = FileSystem().does_file_exist("devdata/env.json")
    if json_exists:
        update_env_json(workspace, ret["token"])
    else:
        create_env_json(workspace, ret["token"])

    click.echo(f"Token expires at {datetime.fromtimestamp(expiry_time)}")
Пример #6
0
 def __init__(self, *args, **kwargs) -> None:
     RequestsLibrary.__init__(self, *args, **kwargs)
     self.logger = logging.getLogger(__name__)
     self.fs = FileSystem()
     self.session_alias_prefix = "rpasession_alias."
     self.current_session_alias = None
Пример #7
0
class UIIPageObject(PageObject):
    download_pdf_locator = "//*[@id='business-case-pdf']/a"
    path_to_downloaded_file = ""
    fs = FileSystem()

    def __init__(self, browser: Selenium, link: str, uii: str,
                 path_to_pdfs_dir: str):
        PageObject.__init__(self, browser, link)
        self.path_to_downloads_dir = self.browser.download_preferences[
            "download.default_directory"]
        self.path_to_pdfs_dir = path_to_pdfs_dir
        self.path_to_pdf_file = ""
        self.uii = uii

    def download_file(self):
        try:
            self.go_to_page()
            self.click_on_file_link()
            self.check_is_file_download()
            self.path_to_pdf_file = self.path_to_downloaded_file
        except Exception as ex:
            raise Exception("Failure download file. Reason:" + str(ex))

    def click_on_file_link(self):
        try:
            self.wait_until_element_appear(locator=self.download_pdf_locator)
            self.remove_block_element()
            self.browser.click_element(self.download_pdf_locator)
        except Exception as ex:
            raise Exception("Unable click on the file link." + str(ex))

    def check_is_file_download(self):
        attempts: int = 10
        timeout: int = 5
        is_success = False
        count = 0
        exception: Exception = Exception()
        while (count < attempts) and (is_success is False):
            try:
                time.sleep(timeout)
                self.find_path_of_downloaded_file()
                is_success = True
            except Exception as ex:
                exception = ex
                count += 1

        if is_success is False:
            print("Error-Retry scope.The file was not downloaded." +
                  str(exception))
            raise exception

    def find_path_of_downloaded_file(self):
        files_from_downloads = list(
            UtilityMethods.get_filepaths_with_oswalk(
                self.path_to_downloads_dir, "(.*pdf$)"))
        self.path_to_downloaded_file = next(
            filter(lambda x: x.lower().find(self.uii.lower()) != -1,
                   files_from_downloads))

        if self.path_to_downloaded_file is None:
            raise Exception(
                "The '.pdf' file wasn't found or the extension is invalid")

    def remove_block_element(self):
        block_element = self.browser.find_element(
            "//*[@id='top-link-block']/a")
        self.browser.driver.execute_script(
            """
                                              var element = arguments[0];
                                              element.parentNode.removeChild(element);
                                              """, block_element)
Пример #8
0
def open_and_complete_form(url: str, constitutional_response: str,
                           csv_filename: str):
    try:
        browser = Browser.Browser()
        browser.new_browser(headless=False)
        browser.new_page(url)
        button_response = "text=" + constitutional_response
        browser.click(selector=button_response)
        pdf = PDF()
        fileSystem = FileSystem()
        print(csv_filename)
        with open(csv_filename) as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            line_count = 0
            if not os.path.exists(run_archive_filepath):
                os.makedirs(run_archive_filepath)
            else:
                fileSystem.empty_directory(run_archive_filepath)
            for row in csv_reader:
                if line_count == 0:
                    line_count += 1
                else:
                    try:
                        print("Completing order " + row[0])
                        #browser.click(selector="id=head")
                        #time.sleep(2)
                        #browser.keyboard_key(action="press", key="ArrowDown")
                        #browser.keyboard_key(action="press", key="Enter")
                        #browser.press_keys('id=head', "Arrowdown 2", "Enter")
                        #browser.click(selector='xpath=//select/option[@value="'+row[1]+'"]')
                        browser.click(
                            selector=
                            'xpath=//form/div/div/div/label[@for="id-body-' +
                            row[2] + '"]')
                        browser.fill_text(
                            selector=
                            'xpath=//div/input[@placeholder="Enter the part number for the legs"]',
                            txt=row[3])
                        browser.fill_text(selector="id=address", txt=row[4])
                        browser.select_options_by("id=head",
                                                  SelectAttribute["value"],
                                                  str(row[1]))
                        browser.click(selector="id=preview")
                        browser.click(selector="id=order")
                        receipt_html_text = browser.get_text(
                            selector="id=receipt")
                        robot_previous_filepath = run_archive_filepath + "\\robot_preview_image_" + str(
                            row[0]) + ".png"
                        browser.wait_for_elements_state(
                            selector="id=robot-preview-image")
                        browser.take_screenshot(
                            selector="id=robot-preview-image",
                            filename=robot_previous_filepath,
                            fullPage=True)
                        receipt_file_path = run_archive_filepath + "\\receipt_file_" + str(
                            row[0])
                        pdf.html_to_pdf(receipt_html_text,
                                        receipt_file_path + ".pdf")
                        browser.click(selector="id=order-another")
                        fileSystem.wait_until_created(robot_previous_filepath)
                        browser.click(selector=button_response)
                        pdf.add_watermark_image_to_pdf(
                            image_path=robot_previous_filepath,
                            output_path=receipt_file_path + "_robot_image.pdf",
                            source_path=receipt_file_path + ".pdf")
                        fileSystem.wait_until_created(path=receipt_file_path +
                                                      "_robot_image.pdf")
                        print("Order complete")
                    except Exception as errorMessage:
                        try:
                            error_message = browser.get_text(
                                selector=
                                'xpath=//div[@class="alert alert-danger"]')
                        except:
                            error_message = errorMessage
                        finally:
                            print("Failed to process order: " +
                                  str(error_message))
                            browser.playwright.close()
                            browser.new_browser(headless=False)
                            browser.new_page(url)
                            button_response = "text=" + constitutional_response
                            browser.click(selector=button_response)

                    finally:
                        print("Getting next order...")

    finally:
        try:
            browser.playwright.close()
        finally:
            print("all orders complete")
Пример #9
0
from RPA.Browser import Browser
from RPA.FileSystem import FileSystem

browser = Browser()  # 需要进行类的实例化。
file_system = FileSystem()  # 进行类的示例化。
url = "http://news.baidu.com"


def store_web_page_content():
    browser.open_available_browser(url)
    text = browser.get_text("body")
    file_system.create_file("output/text.txt", text, overwrite=True)
    browser.screenshot()


def main():
    try:
        store_web_page_content()
    finally:
        browser.close_all_browsers()


if __name__ == '__main__':
    main()
Пример #10
0
from RPA.Browser import Browser
from RPA.FileSystem import FileSystem

browser = Browser()
file_system = FileSystem()
url = "https://robotframework.org/"


def store_web_page_content():
    browser.open_available_browser(url)
    text = browser.get_text("scroller")
    file_system.create_file("output/text.txt", text, overwrite=True)
    browser.screenshot("css:.img-fluid", "output/screenshot.png")


def main():
    try:
        store_web_page_content()
    finally:
        browser.close_all_browsers()


if __name__ == "__main__":
    main()


Пример #11
0
import shutil
import sys

from RPA.Archive import Archive
from RPA.Browser import Browser
from RPA.FileSystem import FileSystem
from RPA.PDF import PDF
from RPA.Robocloud.Secrets import Secrets
from RPA.Robocloud.Items import Items

archive = Archive()
browser = Browser()
pdf = PDF()
secretmanager = Secrets()
workitems = Items()
files = FileSystem()

output_dir = Path(".") / "output"
image_dir = output_dir / "images"
pdf_dir = output_dir / "pdfs"


def main():
    """Robot workflow actions."""
    all_steps_done = False
    try:
        clear_previous_run()  # this can be skipped
        open_page()
        log_in()
        loop_persons()
        collect_the_results()