Python selenium.webdriver.ActionChains() Examples

The following are 30 code examples of selenium.webdriver.ActionChains(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module selenium.webdriver , or try the search function .
Example #1
Source File: tv.py    From Kairos with GNU General Public License v3.0 11 votes vote down vote up
def hover(browser, element, click=False, delay=DELAY_BREAK_MINI):
    action = ActionChains(browser)
    action.move_to_element(element)
    if click:
        time.sleep(delay)
        action.click(element)
    action.perform() 
Example #2
Source File: webelement.py    From knitter with GNU General Public License v3.0 9 votes vote down vote up
def SendEnter(self):
        logger.step_normal("Element [%s]: SendEnter()" % self.__name__, )

        self.__wait()
        elements = Browser.RunningBrowser.find_elements(self.by, self.value)

        action = webdriver.ActionChains(Browser.RunningBrowser)
        action.send_keys_to_element(elements[self.index], Keys.ENTER)
        action.perform() 
Example #3
Source File: WebRunner.py    From PyWebRunner with MIT License 6 votes vote down vote up
def drag_and_drop(self, from_selector, to_selector):
        '''
        Drags an element into another.

        Parameters
        ----------
        from_selector: str
            A CSS selector to search for. This can be any valid CSS selector.
            Element to be dragged.

        to_selector: str
            A CSS selector to search for. This can be any valid CSS selector.
            Target element to be dragged into.

        '''

        from_element = self.get_element(from_selector)
        to_element = self.get_element(to_selector)
        ActionChains(self.browser).drag_and_drop(from_element, to_element).perform() 
Example #4
Source File: test_utils.py    From sos-notebook with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def trigger_keystrokes(browser, *keys):
    """ Send the keys in sequence to the browser.
    Handles following key combinations
    1. with modifiers eg. 'control-alt-a', 'shift-c'
    2. just modifiers eg. 'alt', 'esc'
    3. non-modifiers eg. 'abc'
    Modifiers : http://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html
    """
    for each_key_combination in keys:
        keys = each_key_combination.split('-')
        if len(keys) > 1:  # key has modifiers eg. control, alt, shift
            modifiers_keys = [getattr(Keys, x.upper()) for x in keys[:-1]]
            ac = ActionChains(browser)
            for i in modifiers_keys:
                ac = ac.key_down(i)
            ac.send_keys(keys[-1])
            for i in modifiers_keys[::-1]:
                ac = ac.key_up(i)
            ac.perform()
        else:  # single key stroke. Check if modifier eg. "up"
            browser.send_keys(getattr(Keys, keys[0].upper(), keys[0])) 
Example #5
Source File: webelement.py    From knitter with GNU General Public License v3.0 6 votes vote down vote up
def Set(self, value):
        logger.step_normal("Element [%s]: Set [%s]." % (self.__name__, value))

        value = str(value)

        self.__wait()
        elements = Browser.RunningBrowser.find_elements(self.by, self.value)

        if elements[self.index].tag_name == "select" or elements[self.index].tag_name == "ul":
            self.Select(value)

        else:
            elements[self.index].clear()
            elements[self.index].send_keys(value)

            """
            elements[self.index].clear()
            action = webdriver.ActionChains(Browser.RunningBrowser)
            action.send_keys_to_element(elements[self.index], value)
            action.perform()
            """ 
Example #6
Source File: fuck_bilibili_captcha.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def start_drag(driver, distance):

    # 被妖怪吃掉了
    # knob =  WAIT.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#gc-box > div > div.gt_slider > div.gt_slider_knob.gt_show")))
    # ActionChains(driver).click_and_hold(knob).perform()
    # ActionChains(driver).move_by_offset(xoffset=distance, yoffset=0.1).perform()
    # time.sleep(0.5)
    # ActionChains(driver).release(knob).perform()

    # 被妖怪吃掉了
    # ActionChains(driver).drag_and_drop_by_offset(knob, distance-10, 0).perform()

    knob = WAIT.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#gc-box > div > div.gt_slider > div.gt_slider_knob.gt_show")))
    result = get_path(distance)
    ActionChains(driver).click_and_hold(knob).perform()

    for x in result:
        ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()

    time.sleep(0.5)
    ActionChains(driver).release(knob).perform() 
Example #7
Source File: scraper.py    From fb-ad-archive-scraper with MIT License 6 votes vote down vote up
def process_ad_divs(ad_divs, ad_count, driver, dirname, ad_limit, wait=0):
    # Add whitespace to bottom to allow scrolling to bottom row
    window_height = driver.execute_script('return window.innerHeight')
    driver.execute_script("arguments[0].setAttribute('style', 'margin-bottom:{}px;')".format(window_height),
                          ad_divs[-1])
    processed_add_divs = set()
    for ad_div in ad_divs:
        if ad_count > 0:
            sleep(wait)
        ad_count += 1
        print('Ad {}'.format(ad_count))
        screenshot(ad_div, ad_count, dirname, driver)
        # Click Ad Performance
        ad_div.find_element_by_partial_link_text('See Ad Performance').click()
        webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
        processed_add_divs.add(ad_div)
        if ad_limit == ad_count:
            break

    return processed_add_divs 
Example #8
Source File: WebRunner.py    From PyWebRunner with MIT License 6 votes vote down vote up
def move_to(self, selector, click=False):
        '''
        Move to the element matched by selector or passed as argument.

        Parameters
        ----------
        selector: str
            Any valid CSS selector
        click: bool
            Whether or not to click the element after hovering
            defaults to False
        '''
        try:
            elem = self.get_element(selector)

            action = webdriver.ActionChains(self.browser)
            action.move_to_element(elem)
            if click:
                action.click(elem)

            action.perform()
        except WebDriverException:
            print("move_to isn't supported with this browser driver.") 
Example #9
Source File: test_reconcile.py    From biweeklybudget with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_10_wrong_acct_and_amount(self, base_url, selenium):
        self.baseurl = base_url
        self.get(selenium, base_url + '/reconcile')
        src = selenium.find_element_by_id('ofx-1-OFXT4')
        tgt = selenium.find_element_by_id(
            'trans-3').find_element_by_class_name('reconcile-drop-target')
        # get the innerHTML of both columns
        trans_div = selenium.find_element_by_id('trans-panel').get_attribute(
            'innerHTML')
        ofxtrans_div = selenium.find_element_by_id('ofx-panel').get_attribute(
            'innerHTML')
        # drag and drop
        chain = ActionChains(selenium)
        chain.drag_and_drop(src, tgt).perform()
        # sleep a bit for the drag to stop
        sleep(1)
        # ensure both columns are still the same
        assert selenium.find_element_by_id('trans-panel').get_attribute(
            'innerHTML') == trans_div
        assert selenium.find_element_by_id('ofx-panel').get_attribute(
            'innerHTML') == ofxtrans_div
        # ensure reconciled JS var is still the same
        assert self.get_reconciled(selenium) == {} 
Example #10
Source File: test_reconcile.py    From biweeklybudget with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_09_wrong_amount(self, base_url, selenium):
        self.baseurl = base_url
        self.get(selenium, base_url + '/reconcile')
        src = selenium.find_element_by_id('ofx-1-OFXT4')
        tgt = selenium.find_element_by_id(
            'trans-1').find_element_by_class_name('reconcile-drop-target')
        # get the innerHTML of both columns
        trans_div = selenium.find_element_by_id('trans-panel').get_attribute(
            'innerHTML')
        ofxtrans_div = selenium.find_element_by_id('ofx-panel').get_attribute(
            'innerHTML')
        # drag and drop
        chain = ActionChains(selenium)
        chain.drag_and_drop(src, tgt).perform()
        # sleep a bit for the drag to stop
        sleep(1)
        # ensure both columns are still the same
        assert selenium.find_element_by_id('trans-panel').get_attribute(
            'innerHTML') == trans_div
        assert selenium.find_element_by_id('ofx-panel').get_attribute(
            'innerHTML') == ofxtrans_div
        # ensure reconciled JS var is still the same
        assert self.get_reconciled(selenium) == {} 
Example #11
Source File: test_reconcile.py    From biweeklybudget with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_08_wrong_account(self, base_url, selenium):
        self.baseurl = base_url
        self.get(selenium, base_url + '/reconcile')
        src = selenium.find_element_by_id('ofx-1-OFXT4')
        tgt = selenium.find_element_by_id(
            'trans-4').find_element_by_class_name('reconcile-drop-target')
        # get the innerHTML of both columns
        trans_div = selenium.find_element_by_id('trans-panel').get_attribute(
            'innerHTML')
        ofxtrans_div = selenium.find_element_by_id('ofx-panel').get_attribute(
            'innerHTML')
        # drag and drop
        chain = ActionChains(selenium)
        chain.drag_and_drop(src, tgt).perform()
        # sleep a bit for the drag to stop
        sleep(1)
        # ensure both columns are still the same
        assert selenium.find_element_by_id('trans-panel').get_attribute(
            'innerHTML') == trans_div
        assert selenium.find_element_by_id('ofx-panel').get_attribute(
            'innerHTML') == ofxtrans_div
        # ensure reconciled JS var is still the same
        assert self.get_reconciled(selenium) == {} 
Example #12
Source File: element_operations.py    From warriorframework with Apache License 2.0 6 votes vote down vote up
def _drag_and_drop_by_offset(self, source, **kwargs):
        """Holds down the left mouse button on the source element,
           then moves to the target offset and releases the mouse button
        :Arguments:
            1. source  = a valid WebElement
            2. xoffset = X offset to move to
            3. yoffset = Y offset to move to
        """
        status = True
        print_info("drag and drop an element with offset")
        try:
            xoffset = kwargs.get('xoffset')
            yoffset = kwargs.get('yoffset')
            browser_instance = kwargs.get('browser')
            actions = ActionChains(browser_instance)
            actions.drag_and_drop_by_offset(source, xoffset, yoffset).perform()
        except NoSuchElementException as e:
            print_error("NoSuchElementException occurred")
            status = False
        except Exception as e:
            print_error("An Exception Occurred {}".format(e))
            status = False
        return status 
Example #13
Source File: element_operations.py    From warriorframework with Apache License 2.0 6 votes vote down vote up
def _drag_and_drop(self, source, **kwargs):
        """Send values to a particular element,
        simulates typing into a element
        :Arguments:
            1. source = a valid WebElement
            2. target = a valid WebElement
        """
        status = True
        print_info("Simulate a drag and drop")
        try:
            browser_instance = kwargs.get('browser')
            target = self._get_element(browser_instance,
                                       kwargs.get('target_locator'))
            if source is not None and target is not None:
                ActionChains(browser_instance).drag_and_drop(source,
                                                             target).perform()
        except Exception as e:
            print_error("An Exception Occurred {}".format(e))
            status = False
        return status 
Example #14
Source File: entity.py    From selene with MIT License 6 votes vote down vote up
def hover(self) -> Element:
        actions: ActionChains = ActionChains(self.config.driver)
        self.wait.command('hover', lambda element: actions.move_to_element(element()).perform())
        return self

    # todo: should we reflect queries as self methods? or not...
    # pros: faster to query element attributes
    # cons: queries are not test oriented. test is steps + asserts
    #       so queries will be used only occasionally, then why to make a heap from Element?
    #       hence, occasionally it's enough to have them called as
    #           query.outer_html(element)  # non-waiting version
    #       or
    #           element.get(query.outer_html)  # waiting version
    # def outer_html(self) -> str:
    #     return self.wait.for_(query.outer_html)

    # --- Assertable --- #

    # we need this method here in order to make autocompletion work...
    # unfortunately the "base class" version is not enough 
Example #15
Source File: selenium.py    From SerpScrap with MIT License 5 votes vote down vote up
def _goto_next_page(self):
        """
        Click the next page element,

        Returns:
            The url of the next page or False if there is no such url
                (end of available pages for instance).
        """
        next_url = ''
        element = self._find_next_page_element()

        if hasattr(element, 'click'):
            next_url = element.get_attribute('href')
            try:
                element.click()
            except WebDriverException:
                # See http://stackoverflow.com/questions/11908249/debugging-element-is-not-clickable-at-point-error
                # first move mouse to the next element, some times the element is not visibility
                selector = self.next_page_selectors[self.search_engine_name]
                if selector:
                    try:
                        next_element = WebDriverWait(self.webdriver, 5).until(
                            EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
                        webdriver.ActionChains(self.webdriver).move_to_element(next_element).perform()
                        # wait until the next page link emerges
                        WebDriverWait(self.webdriver, 8).until(
                            EC.visibility_of_element_located((By.CSS_SELECTOR, selector)))
                        element = self.webdriver.find_element_by_css_selector(selector)
                        next_url = element.get_attribute('href')
                        element.click()
                    except WebDriverException:
                        pass

        # wait until the next page was loaded

        if not next_url:
            return False
        else:
            return next_url 
Example #16
Source File: element_operations.py    From warriorframework with Apache License 2.0 5 votes vote down vote up
def _perform_keypress(self, element, **kwargs):
        """
        This function expects to receive a browser instance through the
        "browser" argument and a key "keys" through the kwargs.

        The value for "keys" would be a list of keys tha need to pressed.

        """
        status = True
        flag = False
        keys = kwargs.get('keys')
        actions = ActionChains(element)
        for key in keys:
            try:
                selenium_key = KEYS[key.upper()]
            except KeyError:
                print_error("{0} is not supported by Selenium.".format(key))
                status = False
            else:
                flag = True
                actions.send_keys(selenium_key)
        if flag:
            actions.perform()
            sleep(2)

        return status 
Example #17
Source File: element_operations.py    From warriorframework with Apache License 2.0 5 votes vote down vote up
def _double_click_element(self, element, **kwargs):
        """ Double clicks on the provided element
        :Arguments:
            1. element = a valid WebElement
        """
        status = True
        print_info("Double click on element")
        try:
            browser_instance = kwargs.get('browser')
            ActionChains(browser_instance).double_click(element)
        except Exception as e:
            print_error("An Exception Occurred {}".format(e))
            status = False
        return status 
Example #18
Source File: crawlBaiduWenku.py    From crawlBaiduWenku with MIT License 5 votes vote down vote up
def con_read(browser):  #点击继续阅读
    hidden_div = browser.find_element_by_css_selector('#html-reader-go-more')
    gotBtn = browser.find_element_by_css_selector('.moreBtn')
    actions = webdriver.ActionChains(browser)
    actions.move_to_element(hidden_div)
    actions.click(gotBtn)
    actions.perform()  
    time.sleep(20) 
Example #19
Source File: Screenshot_to_pdf.py    From crawlBaiduWenku with MIT License 5 votes vote down vote up
def con_read(browser):  #点击继续阅读
    hidden_div = browser.find_element_by_css_selector('#html-reader-go-more')
    gotBtn = browser.find_element_by_css_selector('.moreBtn')
    actions = webdriver.ActionChains(browser)
    actions.move_to_element(hidden_div)
    actions.click(gotBtn)
    actions.perform()  
    time.sleep(20) 
Example #20
Source File: entity.py    From selene with MIT License 5 votes vote down vote up
def driver(self) -> WebDriver:
        return self.config.driver

    # @property
    # def actions(self) -> ActionChains:
    #     """
    #     It's kind of just a shortcut for pretty low level actions from selenium webdriver
    #     Yet unsure about this property here:)
    #     comparing to usual high level Selene API...
    #     Maybe later it would be better to make own Actions with selene-style retries, etc.
    #     """
    #     return ActionChains(self.config.driver)

    # --- Element builders --- # 
Example #21
Source File: webui_tests.py    From boardfarm with BSD 3-Clause Clear License 5 votes vote down vote up
def runTest(self):
        print('Checking overview page')
        action_chains = ActionChains(self.driver)
        status_menu = self.driver.find_element_by_xpath("//ul/li/a[contains(text(),'Status')]")
        overview_menu = self.driver.find_element_by_xpath("//ul/li/a[contains(text(),'Overview')]")
        action_chains.move_to_element(status_menu).click(overview_menu).perform()
        self.assertIn('Overview', self.driver.title)
        print('Managed to switch to overview page')
        for i in [ 'System', 'Memory', 'Network', 'DHCP Leases' ]:
            self.driver.find_element_by_xpath("//fieldset/legend[contains(text(),'" + i + "')]")
            print(' * overview page contains section ' + i) 
Example #22
Source File: SeleniumHelper.py    From linkedin-profile-scraper with MIT License 5 votes vote down vote up
def clickSelector(self, selector):
		element = self.getElement(selector)
		if element:
			try:
				actions = webdriver.ActionChains(self.driver)
				actions.move_to_element(element)
				actions.click(element)
				actions.perform()
				return True
			except:
				return False
		return False 
Example #23
Source File: SeleniumHelper.py    From linkedin-profile-scraper with MIT License 5 votes vote down vote up
def clickMultiple(self, selector):
		exit = False
		elements = self.getElements(selector)
		if elements:
			for element in elements:
				try:
					actions = webdriver.ActionChains(self.driver)
					actions.move_to_element(element)
					actions.click(element)
					actions.perform()
					exit = True
				except:
					pass
		return exit 
Example #24
Source File: SeleniumHelper.py    From linkedin-profile-scraper with MIT License 5 votes vote down vote up
def click(self, element):
		actions = webdriver.ActionChains(self.driver)
		actions.move_to_element(element)
		actions.click(element)
		actions.perform() 
Example #25
Source File: SeleniumHelper.py    From linkedin-profile-scraper with MIT License 5 votes vote down vote up
def moveToElement(self, element):
		self.driver.execute_script("return arguments[0].scrollIntoView();", element)
		actions = webdriver.ActionChains(self.driver)
		actions.move_to_element(element)
		actions.perform() 
Example #26
Source File: entity.py    From selene with MIT License 5 votes vote down vote up
def double_click(self) -> Element:
        actions: ActionChains = ActionChains(self.config.driver)
        self.wait.command('double click', lambda element: actions.double_click(element()).perform())
        return self 
Example #27
Source File: entity.py    From selene with MIT License 5 votes vote down vote up
def context_click(self) -> Element:
        actions: ActionChains = ActionChains(self.config.driver)
        self.wait.command('context click', lambda element: actions.context_click(element()).perform())
        return self 
Example #28
Source File: proxy.py    From airtest-selenium with Apache License 2.0 5 votes vote down vote up
def __init__(self, executable_path="chromedriver", port=0,
                 options=None, service_args=None,
                 desired_capabilities=None, service_log_path=None,
                 chrome_options=None):
        if "darwin" in sys.platform:
            os.environ['PATH'] += ":/Applications/AirtestIDE.app/Contents/Resources/selenium_plugin"
        super(WebChrome, self).__init__(chrome_options=chrome_options, executable_path=executable_path,
                                        port=port, options=options, service_args=service_args,
                                        service_log_path=service_log_path, desired_capabilities=desired_capabilities)
        self.father_number = {0: 0}
        self.action_chains = ActionChains(self)
        self.number = 0
        self.mouse = Controller()
        self.operation_to_func = {"elementsD": self.find_any_element, "xpath": self.find_element_by_xpath, "id": self.find_element_by_id,
                                  "name": self.find_element_by_name, "css": self.find_element_by_css_selector} 
Example #29
Source File: client.py    From pwnableweb with Apache License 2.0 5 votes vote down vote up
def chain(self):
    return webdriver.ActionChains(self.browser) 
Example #30
Source File: proxy.py    From airtest-selenium with Apache License 2.0 5 votes vote down vote up
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, options=None):
        super(WebRemote,self).__init__(command_executor=command_executor,
                 desired_capabilities=desired_capabilities, browser_profile=browser_profile, proxy=proxy,
                 keep_alive=keep_alive, file_detector=file_detector, options=options)

        self.father_number = {0: 0}
        self.action_chains = ActionChains(self)
        self.number = 0
        self.mouse=Controller()
        self.operation_to_func={"xpath": self.find_element_by_xpath, "id": self.find_element_by_id,
                                  "name": self.find_element_by_name, "css": self.find_element_by_css_selector}