Esempio n. 1
0
    def __init__(
        self,
        edge_options: Options = None,
        desired_capabilities: dict = None,
        token: str = None,
        project_name: str = None,
        job_name: str = None,
        disable_reports: bool = False,
    ):
        # If no options or capabilities are specified at all, use default Options
        if edge_options is None and desired_capabilities is None:
            caps = Options().to_capabilities()
        else:
            # Specified EdgeOptions take precedence over desired capabilities but either can be used
            caps = (
                edge_options.to_capabilities()
                if edge_options is not None
                else desired_capabilities
            )

        super().__init__(
            capabilities=caps,
            token=token,
            project_name=project_name,
            job_name=job_name,
            disable_reports=disable_reports,
        )
Esempio n. 2
0
 def __init__(
     self,
     edge_options: Options = Options(),
     token: str = None,
     projectname: str = None,
     jobname: str = None,
     disable_reports: bool = False,
 ):
     super().__init__(
         capabilities=edge_options.to_capabilities(),
         token=token,
         projectname=projectname,
         jobname=jobname,
         disable_reports=disable_reports,
     )
Esempio n. 3
0
def build_options(browser, browser_options: List[str],
                  experimental_options: Optional[List[dict]],
                  extension_paths: Optional[List[str]]):
    """ Build the Options object for Chrome or Firefox.

    Args:
        browser: The name of the browser.
        browser_options: The list of options/arguments to include.
        experimental_options: The list of experimental options to include.
        extension_paths: The list of extensions to add to the browser session.

    Examples:
        WebDriverFactory().build_options('chrome', ['headless', 'incognito'], [{'useAutomationExtension', False}])
    """
    browser = browser.lower()
    if browser == Browser.CHROME:
        options = webdriver.ChromeOptions()
    elif browser == Browser.FIREFOX:
        options = webdriver.FirefoxOptions()
    elif browser == Browser.IE:
        options = webdriver.IeOptions()
    elif browser == Browser.OPERA:
        options = webdriver.ChromeOptions()
    elif browser == Browser.EDGE:
        options = Options()
    else:
        raise ValueError(
            f'{browser} is not supported. https://elsnoman.gitbook.io/pylenium/configuration/driver'
        )

    for option in browser_options:
        if option.startswith('--'):
            options.add_argument(option)
        else:
            options.add_argument(f'--{option}')

    if experimental_options:
        for exp_option in experimental_options:
            (name, value), = exp_option.items()
            options.add_experimental_option(name, value)

    if extension_paths:
        for path in extension_paths:
            options.add_extension(path)

    return options
Esempio n. 4
0
def edge(context):
    # -- FIXTURE SETUP
    try:
        edge_options = EdgeOptions()

        if should_use_headless(context):
            print("WARNING: Headless execution is NOT supported by Edge!")
            print("Ignoring headless flag and continuing execution with Edge in full UI mode.")

        # Launch Edge browser with Selenium.
        driver = webdriver.Edge(capabilities=edge_options.to_capabilities())

        # Store reference to Selenium wrapper in Scenario Context so all step definitions & page objects can use it.
        context.selenium = SeleniumWrapper(context, driver)
        yield context.selenium
    except WebDriverException as e:
        print("Selenium WebDriverException raised when initializing Edge!")
        raise e
    # -- FIXTURE CLEANUP
    context.selenium.driver.quit()
Esempio n. 5
0
 def _build_capabilities(self, caps, browser_name):
     options = None
     if caps:
         _, value = caps.popitem()
         try:
             browser = value["browserName"]
         except Exception as e:
             logger.console("No browser name capability was set")
             raise e
         if browser in self.FIREFOX_NAMES:
             options = FirefoxOptions()
         elif browser in self.CHROME_NAMES:
             options = ChromeOptions()
         elif browser in self.IE_NAMES:
             options = IeOptions()
         elif browser == "edge":
             options = Options()
         elif browser == "safari":
             options = DesiredCapabilities.SAFARI.copy()
         for k, v in value.items():
             options.set_capability(k, v)
     else:
         if browser_name in self.FIREFOX_NAMES:
             caps = DesiredCapabilities.FIREFOX.copy()
             options = FirefoxOptions()
         elif browser_name in self.CHROME_NAMES:
             caps = DesiredCapabilities.CHROME.copy()
             options = ChromeOptions()
         elif browser_name in self.IE_NAMES:
             caps = DesiredCapabilities.INTERNETEXPLORER.copy()
             options = IeOptions()
         elif browser_name == "edge":
             caps = DesiredCapabilities.EDGE.copy()
             options = Options()
         elif browser_name == "safari":
             options = DesiredCapabilities.SAFARI.copy()
         for k, v in caps.items():
             options.set_capability(k, v)
     return options
Esempio n. 6
0
def _get_driver():
    driver = None

    # trying with google chrome
    if driver is None:
        try:
            chromedriver_autoinstaller.install()
            driver = webdriver.Chrome()
        except:
            pass

    # trying with edge
    if driver is None:
        try:
            edgedriver_autoinstaller.install()

            driver_options = EdgeOptions()
            driver_options.add_experimental_option("excludeSwitches", ["enable-logging"])

            driver = webdriver.Edge(executable_path="msedgedriver.exe", options=driver_options)
        except:
            pass

    # trying with firefox
    if driver is None:
        try:
            # TODO: firefoxdriver_autoinstaller.install(True);
            driver = webdriver.Firefox(executable_path="msedgedriver.exe")
        except:
            pass

    if (driver):
        driver.implicitly_wait(5)
        return driver
    else:
        raise Exception("Impossible to connect to a browser, download google chrome.")
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.edge.options import Options
from urllib3.packages.six import b

opts = Options()

# opts.add_argument(
#     "user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/71.0.3578.80 Chrome/71.0.3578.80 Safari/537.36"
# )

# driver=webdriver.Edge('Selenium_pract/msedgedriver.exe',edge_options=opts)
driver = webdriver.Edge('Selenium_pract/msedgedriver.exe')

driver.get(
    'https://listado.mercadolibre.com.ec/repuestos-autos-camionetas-bujias')

# Debemos darle click al boton de disclaimer para que no interrumpa nuestras acciones
try:  # Encerramos todo en un try catch para que si no aparece el discilamer, no se caiga el codigo
    disclaimer = driver.find_element(By.XPATH,
                                     '//button[@id="cookieDisclaimerButton"]')
    disclaimer.click()  # lo obtenemos y le damos click
except Exception as e:
    print(e)
    None

while True:
    links_productos = driver.find_elements(
        By.XPATH,
Esempio n. 8
0
    def __init__(self,
                 browser_name,
                 vendor_prefix,
                 port=DEFAULT_PORT,
                 options: Options = None,
                 service_args=None,
                 desired_capabilities=None,
                 service_log_path=DEFAULT_SERVICE_LOG_PATH,
                 service: Service = None,
                 keep_alive=DEFAULT_KEEP_ALIVE):
        """
        Creates a new WebDriver instance of the ChromiumDriver.
        Starts the service and then creates new WebDriver instance of ChromiumDriver.

        :Args:
         - browser_name - Browser name used when matching capabilities.
         - vendor_prefix - Company prefix to apply to vendor-specific WebDriver extension commands.
         - port - Deprecated: port you would like the service to run, if left as 0, a free port will be found.
         - options - this takes an instance of ChromiumOptions
         - service_args - Deprecated: List of args to pass to the driver service
         - desired_capabilities - Deprecated: Dictionary object with non-browser specific
           capabilities only, such as "proxy" or "loggingPref".
         - service_log_path - Deprecated: Where to log information from the driver.
         - keep_alive - Deprecated: Whether to configure ChromiumRemoteConnection to use HTTP keep-alive.
        """
        if desired_capabilities:
            warnings.warn(
                'desired_capabilities has been deprecated, please pass in a Service object',
                DeprecationWarning,
                stacklevel=2)
        if port != DEFAULT_PORT:
            warnings.warn(
                'port has been deprecated, please pass in a Service object',
                DeprecationWarning,
                stacklevel=2)
        self.port = port
        if service_log_path != DEFAULT_SERVICE_LOG_PATH:
            warnings.warn(
                'service_log_path has been deprecated, please pass in a Service object',
                DeprecationWarning,
                stacklevel=2)
        if keep_alive != DEFAULT_KEEP_ALIVE and type(self) == __class__:
            warnings.warn(
                'keep_alive has been deprecated, please pass in a Service object',
                DeprecationWarning,
                stacklevel=2)
        else:
            keep_alive = True

        _ignore_proxy = None
        if not options:
            options = self.create_options()

        if desired_capabilities:
            for key, value in desired_capabilities.items():
                options.set_capability(key, value)

        if options._ignore_local_proxy:
            _ignore_proxy = options._ignore_local_proxy

        self.vendor_prefix = vendor_prefix

        if not service:
            raise AttributeError('service cannot be None')

        self.service = service
        self.service.start()

        try:
            RemoteWebDriver.__init__(
                self,
                command_executor=ChromiumRemoteConnection(
                    remote_server_addr=self.service.service_url,
                    browser_name=browser_name,
                    vendor_prefix=vendor_prefix,
                    keep_alive=keep_alive,
                    ignore_proxy=_ignore_proxy),
                desired_capabilities=desired_capabilities)
        except Exception:
            self.quit()
            raise
        self._is_remote = False
Esempio n. 9
0
 def create_options(self) -> Options:
     return Options()
Esempio n. 10
0
    os.remove("errors.txt")
except FileNotFoundError:
    print("No se ha encontrado archivo de errores")
try:
    os.remove("places.json")
except FileNotFoundError:
    print("No se ha encontrado archivo de places")

try:
    os.remove("papersJson.json")
except FileNotFoundError:
    print("No se ha encontrado archivo de papersJson")

chrome_options = OptionsC()
firefox_options = OptionsF()
edge_options = OptionsE()
edge_options.use_chromium = True

# chrome_options.add_argument("--headless")

term = 'Garcia-Campos+MA'
address = 'https://pubmed.ncbi.nlm.nih.gov/?term=' + term

# firefox = webdriver.Firefox(executable_path=r"E:\Proyects\100tifikmap\webdrivers\geckodriver.exe",
#                             options=firefox_options)
# chrome = webdriver.Chrome(executable_path=r"E:\Proyects\100tifikmap\webdrivers\chromedriver.exe",
#                           options=chrome_options)
edge = webdriver.Edge(
    executable_path=r"E:\Proyects\100tifikmap\webdrivers\msedgedriver.exe")

# firefox.get(address)
Esempio n. 11
0
def test_custom_browser_name():
    options = Options(is_legacy=False)
    options.custom_browser_name = "testbrowsername"
    caps = options.to_capabilities()
    assert caps['browserName'] == "testbrowsername"
Esempio n. 12
0
def driver():
    driver = webdriver.Edge(edge_options=Options(), project_name="Examples", job_name=None)
    yield driver
    driver.quit()
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait

edge_options = Options()
edge_options.use_chromium = True
edge_options.binary_location = 'C:\\Users\\JenkinsUser\\AppData\\Local\\Microsoft\\Edge SxS\\Application\\msedge.exe'

driver = webdriver.Edge(options=edge_options, verbose=True, service_args=['--verbose'])

try:
    driver.set_window_rect(x=10,y=10, width=600, height=600)
    rect = driver.get_window_rect()
    print(rect)
    driver.maximize_window()
    rect = driver.get_window_rect()
    print(rect)
    driver.get('https://bing.com')
finally:
    driver.quit()
Esempio n. 14
0
def options():
    return Options()
Esempio n. 15
0
def test_use_chromium():
    options = Options()
    options.use_chromium = True
    caps = options.to_capabilities()
    assert caps['ms:edgeChromium'] is True
Esempio n. 16
0
def open_browser(executable_path="msedgedriver",
                 edge_args=None,
                 desired_capabilities=None,
                 **kwargs):
    """Open Edge browser instance and cache the driver.

    Parameters
    ----------
    executable_path : str (Default "msedgedriver")
        path to the executable. If the default is used it assumes the
        executable is in the $PATH.
    port : int (Default 0)
        port you would like the service to run, if left as 0, a free port will
        be found.
    desired_capabilities : dict (Default None)
        Dictionary object with non-browser specific capabilities only, such as
        "proxy" or "loggingPref".
    chrome_args : Optional arguments to modify browser settings
    """
    options = Options()
    options.use_chromium = True

    # Gets rid of Devtools listening .... printing
    # other non-sensical error messages
    options.add_experimental_option('excludeSwitches', ['enable-logging'])

    if platform.system().lower() == "windows":
        options.set_capability("platform", "WINDOWS")

    if platform.system().lower() == "linux":
        options.set_capability("platform", "LINUX")

    if platform.system().lower() == "darwin":
        options.set_capability("platform", "MAC")

    # If user wants to re-use existing browser session then
    # he/she has to set variable BROWSER_REUSE_ENABLED to True.
    # If enabled, then web driver connection details are written
    # to an argument file. This file enables re-use of the current
    # chrome session.
    #
    # When variables BROWSER_SESSION_ID and BROWSER_EXECUTOR_URL are
    # set from argument file, then OpenBrowser will use those
    # parameters instead of opening new chrome session.
    # New Remote Web Driver is created in headless mode.
    edge_path = kwargs.get(
        'edge_path', None) or BuiltIn().get_variable_value('${EDGE_PATH}')
    if edge_path:
        options.binary_location = edge_path

    if user.is_root() or user.is_docker():
        options.add_argument("no-sandbox")
    if edge_args:
        if any('--headless' in _.lower() for _ in edge_args):
            CONFIG.set_value('Headless', True)
        for item in edge_args:
            options.add_argument(item.lstrip())
    options.add_argument("start-maximized")
    options.add_argument("--disable-notifications")
    if 'headless' in kwargs:
        CONFIG.set_value('Headless', True)
        options.add_argument("--headless")
    if 'prefs' in kwargs:
        if isinstance(kwargs.get('prefs'), dict):
            prefs = kwargs.get('prefs')
        else:
            prefs = util.prefs_to_dict(kwargs.get('prefs').strip())
        options.add_experimental_option('prefs', prefs)
        logger.warn("prefs: {}".format(prefs))
    driver = Edge(BuiltIn().get_variable_value('${EDGEDRIVER_PATH}')
                  or executable_path,
                  options=options,
                  capabilities=desired_capabilities)
    browser.cache_browser(driver)
    return driver
Esempio n. 17
0
def edge_options():
    return Options()
Esempio n. 18
0
import time
from selenium import webdriver
from selenium.webdriver.common import service
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from bs4 import BeautifulSoup
import xlsxwriter

edge_options = Options()
edge_service = Service("C:\Program Files (x86)\Microsoft\Edge\Application\msedgedriver.exe")
edge_options.add_argument("headless")
driver = webdriver.Edge(service=edge_service)
driver.get("https://store.steampowered.com/search/?sort_by=_ASC&ignore_preferences=1&filter=topsellers")
time.sleep(2)
scroll_pause_time = 1
screen_height = driver.execute_script("return window.screen.height;")
i = 1

workbook = xlsxwriter.Workbook('SteamGames.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold':True})

worksheet.write('A1', 'Name', bold)
worksheet.write('B1', 'Price', bold)
worksheet.write('C1', 'Release Date', bold)
worksheet.write('D1', 'Publisher', bold)
worksheet.write('E1', 'Developer', bold)
worksheet.write('F1', '% Positive Reviews (30 days)', bold)
worksheet.write('G1', 'Total Number Reviews (30 days)', bold)
worksheet.write('H1', '% Positive Reviews (All Time)', bold)
worksheet.write('I1', 'Total Number Reviews (All Time)', bold)
Esempio n. 19
0
def test_use_webview():
    options = Options()
    options.use_webview = True
    caps = options.to_capabilities()
    assert caps['browserName'] == "webview2"
Esempio n. 20
0
URL = "http://orteil.dashnet.org/experiments/cookie/"

STORE_ITEMS = [
    "buyCursor",
    "buyGrandma",
    "buyFactory",
    "buyMine",
    "buyShipment",
    "buyAlchemy lab",
    "buyPortal",
    "buyTime machine",
]
store = []

options = Options()
options.add_argument("window-size=1920,1080")

driver = webdriver.Edge(options=options)
driver.get(URL)

cps = driver.find_element(By.ID, "cps")
money = driver.find_element(By.ID, "money")
cookie = driver.find_element(By.ID, "cookie")

begin = before = now = time.time()

while now - begin < 120:

    while now - before < 5: