Exemple #1
0
def test_lasso_select(output_file_url, selenium):
    plot = generate_plot()

    #limit to one callback on click release
    plot.add_tools(LassoSelectTool(select_every_mousemove=False))

    # Save the plot and start the test
    save(plot)
    selenium.get(output_file_url)
    assert has_no_console_errors(selenium)

    # Drag a lasso selection area around middle point
    canvas = selenium.find_element_by_tag_name('canvas')

    actions = ActionChains(selenium)
    actions.move_to_element_with_offset(canvas, PLOT_DIM * 0.25, PLOT_DIM * 0.25)
    actions.click_and_hold()
    actions.move_by_offset(0, PLOT_DIM * 0.5)
    actions.move_by_offset(PLOT_DIM * 0.5, 0)
    actions.move_by_offset(0, PLOT_DIM * -0.5)
    actions.release()
    actions.perform()

    # Get the alert from box select and assert that the middle item is selected
    alert = selenium.switch_to_alert()
    assert alert.text == 'middle'
Exemple #2
0
 def move(self, delta_x, delta_y):
     """ Move dialog. """
     chain = ActionChains(self.browser)
     chain.click_and_hold(self('dialog_title').element)
     chain.move_by_offset(delta_x, delta_y)
     chain.release(None)
     chain.perform()
def _test_drop_on_component_editor_grid(browser):
    project_dict, workspace_page = startup(browser)

    workspace_page.add_library_item_to_dataflow('openmdao.main.assembly.Assembly', 'top')
    top = workspace_page.get_dataflow_figure('top', '')

    workspace_page.set_library_filter('Assembly')   # put Assembly at top of lib
    assembly = workspace_page.find_library_button('Assembly')

    editor = top.editor_page(double_click=False, base_type='Assembly')
    editor.show_dataflow()

    editor_top = workspace_page.get_dataflow_fig_in_globals('top')

    # sort through these to find the correct 'top'

    chain = ActionChains(browser)
    chain.click_and_hold(assembly)
    chain.move_to_element(editor_top('header').find_element_by_xpath("..")).perform()
    chain.move_by_offset(200, 1).perform()
    chain.release(None).perform()

    # don't bother checking to see if it appeared,
    # the UI box will appear and screw the test if it did

    closeout(project_dict, workspace_page)
def step_impl(context):
        eq2_marker = context.browser.find_element_by_xpath("//body/div[@id='eq']/span[2]/span")
        eq6_marker = context.browser.find_element_by_xpath("//body/div[@id='eq']/span[6]/span")
        actions = ActionChains(context.browser)
        actions.click_and_hold(eq2_marker).move_by_offset(0, 30).release().perform()
        actions.click_and_hold(eq6_marker).move_by_offset(0, 60).release().perform()
        time.sleep(5)
    def set_credit_score_range(self, slider_direction):
        actions = ActionChains(self.driver)
        # Get the pixel width of the slider control
        slider_element = self.driver.find_element_by_xpath(SLIDER)
        slider_width = int(slider_element.get_attribute("scrollWidth"))

        self.logger.info("width: %s" % slider_width)

        element = self.driver.find_element_by_xpath(SLIDER_HANDLE)

        # Move the slider 1/4 of the total width to the right
        if(slider_direction == "right"):
            xOffset = (slider_width/4)
        # Move the slider 1/4 of the total width to the left
        elif(slider_direction == "left"):
            xOffset = (slider_width/-4)
        # Move the slider 1/2 of the total width to the left
        elif(slider_direction == "lowest"):
            xOffset = (slider_width/-2)
        # Move the slider 1/2 of the total width to the right
        elif(slider_direction == "highest"):
            xOffset = (slider_width/2)

        actions.click_and_hold(element)
        actions.move_by_offset(xOffset, 0)
        actions.release()
        actions.perform()
 def add_multiple_textbox_question_to_survey(self):
     self.find_element(self._multiple_textbox_question_locator).click()
     if self.is_multiple_textbox_question_add_displayed:
         actions = ActionChains(self.selenium)
         actions.click_and_hold(self.find_element(self._multiple_textbox_question_locator))
         actions.drag_and_drop(self.find_element(self._multiple_textbox_question_locator),self.find_element(self._question_area_locator))
         actions.perform()
Exemple #7
0
    def setup(self):
        try:
            button = self.window.find_element_by_link_text("Cone")
        except NoSuchElementException:
            print >>sys.stderr, "fatal error: could not find the 'Cone' button!"
            print >>sys.stderr, "(visit %s to diagnose the problem)" % (url)
            raise vtkwebtest.WebTest.Abort()

        button.click()

        # Wait for the vtkweb process to start (but time out after 10 seconds).
        if not vtkwebtest.wait_with_timeout(delay=0.5, limit=10, criterion=found_viewport(self.window)):
            print >>sys.stderr, "fatal error: timed out while waiting for vtkweb process to start"
            raise vtkwebtest.WebTest.Abort()

        # Grab the viewport element so we know where to put the mouse.
        div = self.window.find_element_by_id("viewport")

        # Click-and-drag on the cone to change its position a bit.
        drag = ActionChains(self.window)
        drag.move_to_element(div)
        drag.click_and_hold()
        drag.move_by_offset(-300, 100)
        drag.release()
        drag.perform()

        # Give the page some time to update the image.
        time.sleep(1)
Exemple #8
0
def put_element_on_grid(workspace_page, element_str):
    '''find and get the 'assembly', and the div for the grid object'''
    browser = workspace_page.browser

    for retry in range(3):
        try:
            assembly = workspace_page.find_library_button(element_str)
            chain = ActionChains(browser)
            chain.click_and_hold(assembly)
            chain.move_by_offset(-100, 0).perform()
        except StaleElementReferenceException:
            if retry < 2:
                logging.warning('put_element_on_grid %s:'
                                ' StaleElementReferenceException', element_str)
            else:
                raise
        else:
            break

    grid = browser.find_element_by_xpath('//div[@id="-dataflow"]')
    check_highlighting(grid, True, "Grid")
    release(chain)

    # deal with the modal dialog
    name = NameInstanceDialog(workspace_page).create_and_dismiss()

    # make sure it is on the grid
    ensure_names_in_workspace(workspace_page, [name],
        "Dragging '" + element_str + "' to grid did not produce a new element on page")

    return name
def step_impl(context):
        slider = context.browser.find_element_by_xpath("//body/div[@id='slider-range']")
        height = slider.size['height']
        bottom_marker = context.browser.find_element_by_xpath("//body/div[@id='slider-range']/span[1]")
        actions = ActionChains(context.browser)
        actions.click_and_hold(bottom_marker).move_by_offset(0,-height).release().perform()
        time.sleep(1)
def step_impl(context):
        blue = context.browser.find_element_by_xpath("//body/div[@id='blue']/span")
        width = 300        
        actions = ActionChains(context.browser)
        actions.click_and_hold(blue).move_by_offset(-300, 0).release().perform()
        time.sleep(.5)
        actions.click_and_hold(blue).move_by_offset(41/255 * width, 0).release().perform()
        time.sleep(5)          
def step_impl(context):
        scroller = context.browser.find_element_by_xpath("//body/div[contains(@class,'scroll-pane')]")
        width = scroller.size['width']
        scrollbar = context.browser.find_element_by_xpath("//div[@class='ui-handle-helper-parent']")
        time.sleep(1)
        actions = ActionChains(context.browser)
        actions.click_and_hold(scrollbar).move_by_offset(width/20*17, 0).release().perform()
        time.sleep(1)
def step_impl(context):
        slider = context.browser.find_element_by_xpath("//body/div[@id='slider']")
        width = slider.size['width']
        marker = context.browser.find_element_by_xpath("//body/div[@id='slider']/span")
        actions = ActionChains(context.browser)
        actions.click_and_hold(marker).move_by_offset(-width, 0).release().perform()
        time.sleep(1)
        actions.click_and_hold(marker).move_by_offset(width*0.3, 0).release().perform()
 def add_single_textbox_question_to_survey(self):
     #self.scroll_element_into_view(self._single_textbox_question_locator)
     self.find_element(self._single_textbox_question_locator).click()
     if self.is_single_textbox_question_add_displayed:
         actions = ActionChains(self.selenium)
         actions.click_and_hold(self.find_element(self._single_textbox_question_locator))
         actions.drag_and_drop(self.find_element(self._single_textbox_question_locator),self.find_element(self._question_area_locator))
         actions.perform()
Exemple #14
0
def i_select_a_highlight_on_the_first_page_of_document(step, docnum):
    doc = csss('.edit-document')[int(docnum) - 1]
    el = css("canvas.page-image", doc)
    chain = ActionChains(world.browser)
    chain.move_to_element_with_offset(el, 20, 20)
    chain.click_and_hold(None)
    chain.move_by_offset(300, 100)
    chain.release(None)
    chain.perform()
    def mouse_down_on_link(self, locator):
        """Simulates a mouse down event on a link.

        Key attributes for links are `id`, `name`, `href` and link text. See
        `introduction` for details about locating elements.
        """
        element = self.find_element(locator, tag='link')
        action = ActionChains(self.browser)
        action.click_and_hold(element).perform()
    def mouse_down_on_image(self, locator):
        """Simulates a mouse down event on an image.

        Key attributes for images are `id`, `src` and `alt`. See
        `introduction` for details about locating elements.
        """
        element = self.find_element(locator, tag='image')
        action = ActionChains(self.browser)
        action.click_and_hold(element).perform()
Exemple #17
0
    def mistake(self):
        action = ActionChains(self.driver)
        element = self.driver.find_element_by_xpath(self.selectors['first_paragraph'])
        action.click_and_hold(element)
        action.move_by_offset(0, -20)
        action.perform()
        element.send_keys(Keys.CONTROL + Keys.ENTER)

        """nn-article-header    '//*[@class="nn-article-header"]'"""
def step_impl(context):
        red = context.browser.find_element_by_xpath("//body/div[@id='red']/span")
        red_main = context.browser.find_element_by_xpath("//body/div[@id='red']/div")
        width = red_main.size['width']
        print(width)
        actions = ActionChains(context.browser)
        actions.click_and_hold(red).move_by_offset(-300, 0).release().perform()
        time.sleep(.5)
        actions.click_and_hold(red).move_by_offset(217/255 * width, 0).release().perform()
        time.sleep(.5)
    def mouse_down_on_image(self, locator):
        """Simulates a mouse down event on an image identified by ``locator``.

        See the `Locating elements` section for details about the locator
        syntax. When using the default locator strategy, images are searched
        using ``id``, ``name``, ``src`` and ``alt``.
        """
        element = self.find_element(locator, tag='image')
        action = ActionChains(self.driver)
        action.click_and_hold(element).perform()
    def mouse_down_on_link(self, locator):
        """Simulates a mouse down event on a link identified by ``locator``.

        See the `Locating elements` section for details about the locator
        syntax. When using the default locator strategy, links are searched
        using ``id``, ``name``, ``href`` and the link text.
        """
        element = self.find_element(locator, tag='link')
        action = ActionChains(self.driver)
        action.click_and_hold(element).perform()
Exemple #21
0
def solve_14(event_names):
    image_size = 186
    offsets = [2 * image_size, 2 * image_size, image_size, image_size]
    for event_name, offset in zip(event_names, offsets):
        element = driver.find_element_by_xpath("//li[@data-id='{0}']".format(event_name))
        action_chain = ActionChains(driver)
        action_chain.click_and_hold(element)
        action_chain.move_by_offset(-offset, 0)
        action_chain.release()
        action_chain.perform()
def movePieceToPuzzle(_driver, _piece, _GP, _P1, _P2):
    gx1, gy1 = _GP
    x2, y2 = _P1
    #print("Piece Coord : " + str(_P2[0]) + "," + str(_P2[1]))
    # x2 = x2 + _P2[0] - 50
    # y2 = y2 + _P2[1] - 50
    actionChains = ActionChains(_driver)
    actionChains.move_to_element(_piece)
    actionChains.perform()
    actionChains.click_and_hold(_piece)

    xOffset = 0
    yOffset = 0
    speed = 5

    """Slant movement as far as possible."""
    if(gx1 < x2):
        slope = int(round((y2 - gy1) / (x2 - gx1)))
        if(slope > 0):
            slope *= -1
        xOffset = 1 * speed
        while(gx1 <= x2 and gy1 >= y2):
            actionChains.move_by_offset(xOffset, slope * speed)
            gx1 += xOffset
            gy1 += slope * speed
        actionChains.move_by_offset(gx1 - x2, slope * speed)
        gy1 += slope * speed
    elif(gx1 > x2):
        slope = int(round((y2 - gy1) / (x2 - gx1)))
        if(slope > 0):
            slope *= -1
        xOffset = -1 * speed
        while(x2 <= gx1 and gy1 >= y2):
            actionChains.move_by_offset(xOffset, slope * speed)
            gx1 += xOffset
            gy1 += slope * speed
        actionChains.move_by_offset(x2 - gx1, slope * speed)
        gy1 += slope * speed

    #Remaining distance by robotic
    if(gy1 > y2):
        yOffset = -1 * speed
        while(gy1 >= y2):
            actionChains.move_by_offset(0, yOffset)
            gy1 += yOffset
        actionChains.move_by_offset(0, y2 - gy1)
    elif(gy1 < y2):
        yOffset = 1 * speed
        while(gy1 <= y2):
            actionChains.move_by_offset(0, yOffset)
            gy1 += yOffset
        actionChains.move_by_offset(0, gy1 - y2)
    
    actionChains.release()
    actionChains.perform()
Exemple #23
0
    def isc_test(self):
        pla = platform_get()
        pla.get('/explore')
        pla.wait_new_page("//b[contains(text(), 'Seismic Hazard Data Sets and Models')]",
                          "/explore", strategy="next", timeout=10)

        #  <li>
        #  <a href="/maps/23">
        enter_button = pla.xpath_finduniq(
            "//li/a[@href='/maps/23' and normalize-space(text()) = 'Global "
            "Instrumental Earthquake Catalogue (1900 - 2009)']")
        enter_button.click()
        pla.wait_new_page(enter_button, '/maps/23')

        enter_button = pla.xpath_finduniq(
            "//a[@href='/maps/23/view' and "
            "normalize-space(text()) = 'View Map']")
        enter_button.click()
        pla.wait_new_page(enter_button, '/maps/23/view', timeout=15)

        # <button id="ext-gen159" class=" x-btn-text gxp-icon-getfeatureinfo"
        # type="button">Identify
        enter_button = pla.xpath_finduniq(
            "//button[@type='button' and normalize-space(text())"
            "= 'Identify']", 50)
        enter_button.click()

        action = ActionChains(pla.driver)
        action.move_by_offset(500, 400)
        action.click_and_hold()
        action.move_by_offset(150, 150)
        action.release()
        action.perform()

        time.sleep(3)

        # wait info button will be clicked
        pla.xpath_finduniq(
            "//button[@type='button' and normalize-space(text())"
            "= 'Identify']/../../../../..[contains(concat(' ', @class, ' '),"
            " ' x-btn-pressed ')]", 100)

        tile = pla.xpath_finduniq(
            "//img[contains(@src, 'wms?LAYERS=oqplatform%3Aisc_viewer_measure"
            "&FORMAT=image%2Fpng&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1"
            "&REQUEST=GetMap&STYLES=&TILED=true&SRS=EPSG%3A900913&BBOX="
            "-10018754.17,0,-5009377.085,5009377.085&WIDTH=256&HEIGHT=256')]",
            50)

        action = ActionChains(pla.driver)
        action.move_to_element_with_offset(tile, 107, 115)
        action.click()
        action.perform()

        pla.xpath_finduniq("//div[text() = '1951-03-19T04:23:00']", 50)
    def test_teacher_green_check_icon_is_displayed_for_completed_14814(self):
        """Green check icon is displayed for completed assignments.

        Steps:
        If the user has more than one course, click on a CC course name
        Click "View Detailed Scores

        Expected Result:
        Green check icon is displayed for completed assignments
        """
        self.ps.test_updates['name'] = 'cc2.08.011' \
            + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = ['cc2', 'cc2.08', 'cc2.08.011', '14814']
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        self.teacher.wait.until(
            expect.visibility_of_element_located(
                (By.XPATH, '//a[contains(text(),"View Detailed Scores")]')
            )
        ).click()
        self.teacher.wait.until(
            expect.visibility_of_element_located(
                (By.XPATH, '//span[contains(text(),"Student Scores")]')
            )
        )
        # scroll to find a green checkmark
        assignments = self.teacher.find_all(
            By.XPATH,
            "//span[contains(@aria-describedby,'header-cell-title')]")

        for i in range(len(assignments)//4):
            try:
                self.teacher.find(
                    By.XPATH,
                    '//span[contains(@class,"trig")]' +
                    '//*[contains(@class,"finished")]')
                break
            except (NoSuchElementException, ElementNotVisibleException):
                if i >= (len(assignments)//4)-1:
                    print("completed assignments for this period")
                    raise Exception
                # try to drag scroll bar instead of scrolling
                scroll_bar = self.teacher.find(
                    By.XPATH,
                    '//div[contains(@class,"ScrollbarLayout_faceHorizontal")]')
                actions = ActionChains(self.teacher.driver)
                actions.move_to_element(scroll_bar)
                actions.click_and_hold()
                actions.move_by_offset(50, 0)
                actions.release()
                actions.perform()

        self.ps.test_updates['passed'] = True
def set_freq_to_10(selenium):
    """
    Set the frequency slider to 10%
    """
    ac = ActionChains(selenium)
    el = selenium.find_element_by_xpath('//a[@class="ui-slider-handle ui-state-default ui-corner-all"]')
    ac.move_to_element(el)
    ac.click_and_hold()
    ac.move_by_offset(80, 0)
    ac.release()
    ac.perform()
Exemple #26
0
def klickElement(element):
    print("Klikkin elemendil: "+element.text)
    #actionite läbiviija browseri külge
    actions = ActionChains(browser)
    #liigub nupu juurde
    actions.move_to_element(element)
    #vajutab
    actions.click_and_hold()
    #viib läbi eelnevalt kirjeldatud liigutused
    actions.release()
    actions.perform()
Exemple #27
0
 def drag_element_at_position(self, element, x, y, dx, dy, mod=None):
     actions = ActionChains(self._driver)
     if mod:
         actions.key_down(mod)
     actions.move_to_element_with_offset(element, x, y)
     actions.click_and_hold()
     actions.move_by_offset(dx, dy)
     actions.release()
     if mod:
         actions.key_up(mod)
     actions.perform()
Exemple #28
0
def hard_click(el):
    """
    Sometimes selenium seems to be unable to properly click.  This is more
    reliable.
    """
    #href = el.get_attribute("href")
    #world.browser.get(href)
    chain = ActionChains(world.browser)
    chain.click_and_hold(el)
    chain.release(None)
    chain.perform()
def drag_element_to(browser, element, drag_to, centerx):
    '''Drag one element over to another element'''
    chain = ActionChains(browser)
    chain.move_to_element(element).perform()
    chain.click_and_hold(element)
    chain.move_to_element(drag_to).perform()
    if centerx:
        chain.move_by_offset(int(drag_to.value_of_css_property('width')[:-2])/2, 1).perform()
    else:
        chain.move_by_offset(2, 1).perform()
    return chain
def resize_editor(workspace_page, editor):
    '''ensure that the editor is not covering the library (or else we cannot drag things from it!)'''
    browser = workspace_page.browser

    page_width = browser.get_window_size()['width']
    lib_width = workspace_page('library_tab').find_element_by_xpath('..').size['width']
    lib_position = workspace_page('library_tab').find_element_by_xpath('..').location['x']
    dialog_width = editor('dialog_title').find_element_by_xpath('../..').size['width']
    dialog_position = editor('dialog_title').find_element_by_xpath('../..').location['x']

    # how much overlap do we have?
    overlap = lib_position - (dialog_position + dialog_width)

    if overlap < 0:  # we are overlapping
        # check to see if we have enough room to move out of the way
        if page_width < dialog_width + lib_width:
            # not enough, need to rezize the editor

            # look for the resize handle
            sibblings = editor('dialog_title').find_elements_by_xpath('../../div')
            handle = None
            for sib in sibblings:
                if "ui-resizable-se" in sib.get_attribute('class'):
                    handle = sib

            # do the resizing
            chain = ActionChains(browser)
            chain.click_and_hold(handle)
            chain.move_by_offset(450 - dialog_width, 0).perform()  # we can resize editor down to 425px, any less and we cover drop targets
            chain.click().perform()  # must click because release is not working. why? I do not know.
            chain.release(None).perform()

            # recalculate the overlap
            dialog_width = editor('dialog_title').find_element_by_xpath('../..').size['width']
            dialog_position = editor('dialog_title').find_element_by_xpath('../..').location['x']
            overlap = lib_position - (dialog_position + dialog_width)

        # We are good, move out!
        chain = ActionChains(browser)
        chain.click_and_hold(editor('dialog_title').element)
        chain.move_by_offset(overlap, 0).perform()
        chain.click().perform()  # must click because release is not working. why? I do not know.
        chain.release(None).perform()

        # recalculate the overlap
        dialog_width = editor('dialog_title').find_element_by_xpath('../..').size['width']
        dialog_position = editor('dialog_title').find_element_by_xpath('../..').location['x']
        overlap = lib_position - (dialog_position + dialog_width)

        if overlap < 0:
            # we still have a problem.
            eq(True, False,
                "Could not move or rezise the editor dialog so it is not " \
                "overlapping the library. The browser window is too small")
def pan_plot(selenium, pan_x=None, pan_y=None):
    canvas = selenium.find_element_by_tag_name('canvas')
    wait_for_canvas_resize(canvas, selenium)
    # Enable the pan tool
    pan_buttons = selenium.find_elements_by_css_selector(
        '.bk-button-bar-list[type="pan"] .bk-toolbar-button')
    pan_button = pan_buttons[0]
    if 'active' not in pan_button.get_attribute('class'):
        pan_button.click()

    actions = ActionChains(selenium)
    actions.move_to_element_with_offset(canvas, 200, 200)
    actions.click_and_hold()
    actions.move_by_offset(pan_x, pan_y)
    actions.release()
    actions.perform()
def zoom_plot(selenium):
    canvas = selenium.find_element_by_tag_name('canvas')
    wait_for_canvas_resize(canvas, selenium)
    # Enable the box zoom tool
    pan_buttons = selenium.find_elements_by_css_selector(
        '.bk-button-bar-list[type="pan"] .bk-toolbar-button')
    zoom_button = pan_buttons[1]
    if 'active' not in zoom_button.get_attribute('class'):
        zoom_button.click()

    actions = ActionChains(selenium)
    actions.move_to_element_with_offset(canvas, 30, 30)
    actions.click_and_hold()
    actions.move_by_offset(200, 200)
    actions.release()
    actions.perform()
Exemple #33
0
 def swiper_valid(self):
     builder = ActionChains(self.driver)
     builder.reset_actions()
     track = self.move_mouse(300)
     builder.move_to_element(
         self.driver.find_element_by_class_name("btn_slide"))
     builder.click_and_hold()
     time.sleep(0.2)
     for i in track:
         builder.move_by_offset(xoffset=i, yoffset=0)
         builder.reset_actions()
     time.sleep(0.1)
     # 释放左键,执行for中的操作
     builder.release().perform()
     time.sleep(5)
     self.swiper_valid()
Exemple #34
0
def test_box_select(output_file_url, selenium):
    PLOT_DIM = 600

    source = ColumnDataSource(
        dict(
            x=[1, 2, 3],
            y=[3, 2, 3],
            name=['top_left', 'middle', 'top_right'],
        ))
    # Make plot and add a taptool callback that generates an alert
    plot = figure(tools='box_select',
                  height=PLOT_DIM,
                  width=PLOT_DIM,
                  x_range=[1, 3],
                  y_range=[1, 3])
    plot.circle(x='x', y='y', radius=0.2, source=source)

    source.callback = CustomJS(code="""
        var indices = cb_obj.get('selected')['1d'].indices,
            data = cb_obj.get('data'),
            selected_names = '';

        Bokeh.$.each(indices, function(i, index) {
            selected_names += data['name'][index];
        });

        alert(selected_names);
    """)

    # Save the plot and start the test
    save(plot)
    selenium.get(output_file_url)

    # Drag a box zoom around middle point
    canvas = selenium.find_element_by_tag_name('canvas')

    actions = ActionChains(selenium)
    actions.move_to_element_with_offset(canvas, PLOT_DIM * 0.25,
                                        PLOT_DIM * 0.25)
    actions.click_and_hold()
    actions.move_by_offset(PLOT_DIM * 0.5, PLOT_DIM * 0.5)
    actions.release()
    actions.perform()

    # Get the alert from box select and assert that the middle item is selected
    alert = selenium.switch_to_alert()
    assert alert.text == 'middle'
Exemple #35
0
def pass_captcha(browser):
    # try:
    WebDriverWait(browser, 10).until(
        expected_conditions.presence_of_element_located(
            (By.ID, "tcaptcha_iframe")))
    browser.switch_to.frame('tcaptcha_iframe')
    WebDriverWait(browser, 10).until(
        expected_conditions.presence_of_element_located((By.ID, "slideBg")))
    WebDriverWait(browser, 10).until(
        expected_conditions.presence_of_element_located((By.ID, "slideBlock")))
    img_bg = browser.find_element_by_id('slideBg')
    img_slide = browser.find_element_by_id('slideBlock')
    try:
        bg_src = wait_attribute_get(img_bg, 'src')
        slide_position = wait_attribute_get(img_slide, 'style', contain='top')
    except TimeoutError:
        raise

    # load image background
    bg_urlparse = urlparse(bg_src)
    if not bg_urlparse.scheme:
        bg_src = urljoin('https://hy.captcha.qq.com', bg_urlparse.geturl())

    img_fp = BytesIO(get_data_from_url(bg_src))
    imgsrc, pixels = img_threshold(img_fp)
    # imgsrc, pixels = img_threshold(img_fp, 'hahahahaha.jpg')

    rex = re.compile('top:\s*(\d+)px')
    slide_top = int(rex.search(slide_position).group(1)) * 2
    rex = re.compile('left:\s*(\d+)px')
    slide_left = int(rex.search(slide_position).group(1)) * 2
    block_border = scan_gap_position(imgsrc, pixels,
                                     slide_top + SLIDE_SIZE.y_start)

    drag_thumb = browser.find_element_by_id('tcaptcha_drag_thumb')
    action_chains = ActionChains(browser)
    action_chains.click_and_hold(drag_thumb)
    distance = (block_border - SLIDE_SIZE.x_start - slide_left) / 2

    last_offset = 0
    for i in generate_slide_locus(distance, 0.8, interval=15):
        action_chains.move_by_offset(int(i - last_offset), 0)

        last_offset = i
        # time.sleep(0.5)
    action_chains.release()
    action_chains.perform()
Exemple #36
0
def test_invest_buy_bucket(selenium, live_server, client):
    """
    Test buying a bucket
    """
    user = User.objects.create_user('temporary', '*****@*****.**', 'temporary')
    user.save()
    user.userbank.create(
        item_id='dummy1', access_token='dummy2',
        institution_name='dummy3', current_balance_field=0,
        account_name_field="dummy4", income_field=0,
        expenditure_field=0
    )
    stock = Stock(
        name="Name1", ticker="poooooop"
    )
    stock.save()
    stock.daily_quote.create(
        value=10000, date="2016-03-03"
    )
    client.login(username='******', password='******')
    cookie = client.cookies['sessionid']
    buck = InvestmentBucket.create_new_bucket(
        name="IAMATESTBUCKET", public=True,
        owner=user.profile)
    buck.save()
    InvestmentStockConfiguration(quantity=1, stock=stock, bucket=buck, start="2016-03-03").save()
    assert user.profile.owned_bucket.count() == 1
    selenium.get('%s%s' % (live_server, '/login'))
    selenium.add_cookie({
        'name': 'sessionid',
        'value': cookie.value,
        'secure': False,
        'path': '/',
    })
    selenium.get('%s%s' % (live_server, '/home'))
    selenium.implicitly_wait(10)
    selenium.find_element_by_xpath("//button[contains(.,'Invest')]").click()
    slider = selenium.find_element_by_class_name("rc-slider-handle")
    actions = ActionChains(selenium)
    actions.click_and_hold(slider)
    actions.move_by_offset(100, 0)
    actions.release(slider)
    actions.perform()
    save_composition = selenium.find_element_by_id("save")
    save_composition.click()
    assert user.profile.trading_accounts.get(account_name='default').buckettrades.count() == 1
Exemple #37
0
    def mouse_down(self, locator: Union[WebElement, str]):
        """Simulates pressing the left mouse button on the element ``locator``.

        See the `Locating elements` section for details about the locator
        syntax.

        The element is pressed without releasing the mouse button.

        See also the more specific keywords `Mouse Down On Image` and
        `Mouse Down On Link`.
        """
        self.info(f"Simulating Mouse Down on element '{locator}'.")
        element = self.find_element(locator)
        # _unwrap_eventfiring_element can be removed when minimum required Selenium is 4.0 or greater.
        element = _unwrap_eventfiring_element(element)
        action = ActionChains(self.driver)
        action.click_and_hold(element).perform()
def test_dbsv005_mouse_selection(dash_duo):

    app = dash.Dash(__name__)

    app.layout = html.Div(
        user_interactions_layout(
            dash_bio.SequenceViewer(id=_COMPONENT_ID, sequence=_data)))

    user_interactions_callback(app,
                               dash_duo,
                               component_id=_COMPONENT_ID,
                               prop_name='mouseSelection')

    output_div = dash_duo.find_element('#interaction-results')

    sequence = dash_duo.find_element('.fastaSeq')

    ac = ActionChains(dash_duo.driver)
    ac.move_to_element(sequence)
    ac.move_by_offset(-(sequence.size['width'] / 2),
                      -(sequence.size['height'] / 2))
    ac.click_and_hold()
    ac.move_by_offset(85, 0)
    ac.release()
    ac.perform()

    expected_info = {'selection': 'MALWMRLLPL', 'start': 1, 'end': 10}

    assert output_div.get_attribute('innerHTML') == json.dumps(expected_info)

    # select something else

    ac = ActionChains(dash_duo.driver)
    ac.move_to_element(sequence)
    ac.move_by_offset(-(sequence.size['width'] / 2 - 100),
                      -(sequence.size['height'] / 2 - 20))
    ac.click_and_hold()
    ac.move_by_offset(55, 0)
    ac.release()
    ac.perform()

    expected_info = {'selection': 'PKTRREA', 'start': 52, 'end': 58}

    assert output_div.get_attribute('innerHTML') == json.dumps(expected_info)

    ac.send_keys(Keys.ESCAPE)
Exemple #39
0
    def mouse_down(self, locator):
        """Simulates pressing the left mouse button on the element ``locator``.

        See the `Locating elements` section for details about the locator
        syntax.

        The element is pressed without releasing the mouse button.

        See also the more specific keywords `Mouse Down On Image` and
        `Mouse Down On Link`.
        """
        self._element_meta(self.find_element(locator))

        self.info("Simulating Mouse Down on element '%s'." % locator)
        element = self.find_element(locator)
        action = ActionChains(self.driver)
        action.click_and_hold(element).perform()
    def adjust_var_axes_slider(self, var, axis, min_offset_percent, max_offset_percent):
        var_row_elements = self._get_var_row_elements()
        print("...# of var_row_elements: {n}".format(n=len(var_row_elements)))
        for r in var_row_elements:
            var_axes_row_locator = ".//div[starts-with(@class, 'col-sm')]//button"
            buttons = r.find_elements_by_xpath(var_axes_row_locator)
            for b in buttons:
                if b.text == var:
                    div_index_for_axis = 0
                    var_axes_locator = ".//div[@class='collapse show']/div"
                    var_axes_elements = r.find_elements_by_xpath(var_axes_locator)
                    # number of var_axes_elements should be the number of sliders
                    # find the axis to be modified.
                    axis_locator = ".//div[@class='row']/div[@class='col-auto']"
                    for an_axis in var_axes_elements:
                        axis_title_elements = an_axis.find_elements_by_xpath(axis_locator)
                        # print("...an axis...{t}".format(t=axis_title_elements[0].text))
                        if axis_title_elements[0].text == axis:
                            print("FOUND the axis to be adjusted...{i}".format(i=div_index_for_axis))
                            break
                        else:
                            div_index_for_axis += 1

                    # index to var_axes_elements
                    the_axis = var_axes_elements[div_index_for_axis]
                    the_axis_title_element = the_axis.find_elements_by_xpath(axis_locator)[0]
                    print("...the_axis_title_element's text: {t}".format(t=the_axis_title_element.text))

                    # get the slider track width
                    slider_track_locator = ".//div[@class='slider-tracks']/div"
                    slider_track = the_axis.find_element_by_xpath(slider_track_locator)
                    slider_width = slider_track.size['width']
                    print("...info...width of slider_track: {w}".format(w=slider_width))
                    # get the slider handle elements - this is the min and max handles
                    slider_handle_locator = ".//div[@class='slider-handles']/div[@role='slider']"
                    min_max_elements = the_axis.find_elements_by_xpath(slider_handle_locator)
                    ac = ActionChains(self.driver)
                    if min_offset_percent != 0:
                        min_offset = (min_offset_percent/100) * slider_width
                        ac.click_and_hold(min_max_elements[0]).move_by_offset(min_offset, 0).release().perform()
                        time.sleep(self._delay)
                    if max_offset_percent != 0:
                        max_offset = (max_offset_percent/100) * slider_width
                        ac.click_and_hold(min_max_elements[1]).move_by_offset(max_offset, 0).release().perform()
                        time.sleep(self._delay)
                    break
Exemple #41
0
    def temperatureMeasurement(self, x, y, x0=0, y0=0, mode='MULTI'):
        '''
        温度测量控件:
        对该模块的测试点:
        1.按钮通用状态测试:未选中状态、选中状态、悬停状态。方案:检查图片名
        2.选中状态的有效性:单点模式、多点模式、单区域模式。方案:检查选中后的功能是否匹配
        3.测温准确度检查:返回正常值、值是否正确(建议通过接口直接检查)
        4.返回值检查(建议通过接口测试检测)

        *备注:控件的(0,0)坐标位置在控件的左上角
        '''

        #温度测量入口
        self.driver.find_element_by_id('btn_Set_cw').click()
        #操作模式选择
        if 'MULTI' == mode:
            #多点模式操作
            self.driver.find_element_by_id(
                'btn_cw_continue').click()  # 单点测温模式选择
            temp = self.driver.find_element_by_id('cavars')
            ActionChains(driver).move_to_element_with_offset(
                temp, x, y).click().perform()  # 确定点击位置
            time.sleep(10)

        elif 'SINGLE' == mode:
            #单点模式操作
            self.driver.find_element_by_id('btn_cw_single').click()  #单点测温模式选择
            temp = self.driver.find_element_by_id('cavars')
            ActionChains(driver).move_to_element_with_offset(
                temp, x, y).click().perform()  # 确定点击位置
            time.sleep(10)

        elif 'AREA' == mode:
            #区域模式
            self.driver.find_element_by_id('btn_cw_area').click()  #区域测温模式选择
            temp = self.driver.find_element_by_id('cavars')
            action = ActionChains(driver).move_to_element_with_offset(
                temp, x0, y0)  #选择起始位置
            action.click_and_hold().move_by_offset(
                x, y).release().perform()  #画矩形区域
            time.sleep(10)

        else:
            print('选择模式错误:必须为SINGLE、MULTI、AREA模式之一')
        #退出测温模式
        self.driver.find_element_by_id('btn_Set_cw').click()
Exemple #42
0
 def filter_by_price(self):
     WebDriverWait(self.driver, 5).until(
         EC.element_to_be_clickable(
             (By.XPATH, "//*[contains(text(),'Pricing')]"))).click()
     self.slider_min = WebDriverWait(self.driver, 5).until(
         EC.element_to_be_clickable(
             (By.XPATH,
              "//*[@class='rz-pointer rz-pointer-min rz-active']")))
     move = ActionChains(self.driver)
     move.click_and_hold(self.slider_min).move_by_offset(
         500, 0).release().perform()
     self.slider_max = WebDriverWait(self.driver, 5).until(
         EC.element_to_be_clickable(
             (By.XPATH, "//*[@class='rz-pointer rz-pointer-max']")))
     move = ActionChains(self.driver)
     move.click_and_hold(self.slider_max).move_by_offset(
         -50, 0).release().perform()
Exemple #43
0
 def forgetPwd(self):
     time.sleep(2)
     self.driver.find_element_by_xpath('//*[@id="root"]/section/div[1]/div/div[3]/div/div/div[1]/form/div[3]/div/div/span/a').click()  # 点击忘记密码
     time.sleep(2)
     self.driver.find_element_by_xpath('//*[@id="mobile"]').send_keys(read_resource("${thelenderphone}"))  # 输入手机号
     #====================
     #可以实现鼠标拖动,但效果不佳
     source = self.driver.find_element_by_xpath('//*[@id="ResetBlockUnlockSlider"]')
     ac = ActionChains(self.driver)
     ac.click_and_hold(source)
     for i in range(50):
         ac.move_by_offset(6.18,0).perform()
         text = self.driver.find_element_by_xpath('//*[@id="ResetBlockUnlockSlider"]').get_attribute("style")
         print(text)
     time.sleep(2)
     ac.release().perform()
     self.driver.find_element_by_xpath('//*[@id="root"]/section/div[1]/div/div[2]/div/div/form/div[2]/div[2]/div/div/span/button').click()  # 下一步
Exemple #44
0
 def select_size_target(self, select_id=None):
     self.waitForReloadFinish("add-to-cart-button")
     if select_id is None or select_id == "":
         return
     current_url = self.driver.current_url
     try:
         actions = ActionChains(self.driver)
         searchDropDown = self.driver.find_element_by_id('native_dropdown_selected_size_name')
         actions.move_to_element(searchDropDown)
         actions.click_and_hold(searchDropDown)
         actions.perform()
         waitRandomSecons()
         select = Select(searchDropDown)
         select.select_by_visible_text(select_id)
         actions.send_keys(Keys.RETURN).perform()
     except Exception, e:
         self.openUrl(current_url, "add-to-cart-button")
Exemple #45
0
    def mouse_down(self, locator):
        """Simulates pressing the left mouse button on the element specified by `locator`.

        The element is pressed without releasing the mouse button.

        Key attributes for arbitrary elements are `id` and `name`. See
        `introduction` for details about locating elements.

        See also the more specific keywords `Mouse Down On Image` and
        `Mouse Down On Link`.
        """
        self.info("Simulating Mouse Down on element '%s'" % locator)
        element = self.find_element(locator, required=False)
        if element is None:
            raise AssertionError("ERROR: Element %s not found." % (locator))
        action = ActionChains(self.browser)
        action.click_and_hold(element).perform()
Exemple #46
0
    def shake(self):
        """ Simulates a shake of the screen

        By shaking, the current topology information will be updated in
        browser's localstorage
        """
        # shake the screen once to update localstorage
        action = ActionChains(self._selenium.driver)
        element = self._selenium.get_webelement('//body')
        action.move_to_element_with_offset(element,0, 0).perform()
        action.move_to_element_with_offset(element,200,200).perform()
        action.click_and_hold(element).perform()
        action.move_by_offset(1,0).perform()
        action.move_by_offset(-1,0).perform()
        action.release().perform()
        self.refresh_canvas()
        BuiltIn().log("Shaked the canvas once")
Exemple #47
0
    def drag(self, source_index, target_index, after=True):
        """
        Gets the drag handle with index source_index (relative to the vertical layout of the page)
        and drags it to the location of the drag handle with target_index.

        This should drag the element with the source_index drag handle AFTER the
        one with the target_index drag handle, unless 'after' is set to False.
        """
        draggables = self.q(css='.drag-handle')
        source = draggables[source_index]
        target = draggables[target_index]
        action = ActionChains(self.browser)
        action.click_and_hold(source).perform()  # pylint: disable=protected-access
        action.move_to_element_with_offset(
            target, 0, target.size['height'] / 2 if after else 0
        ).perform()  # pylint: disable=protected-access
        action.release().perform()
 def testRun(self):
     try:
         driver = webdriver.Chrome(executable_path="./drivers/chromedriver.exe")
         driver.maximize_window()
         driver.get("https://sfo-demo.herokuapp.com/model-portfolio")
         driver.implicitly_wait(8)
         #Select “All Weather Strategy” by clicking on “Explore Investment Ideas”
         explore_Investment_Ideas_button= driver.find_element_by_xpath("//*[contains(text(),'Explore Investment Ideas') and @href = 'weather_portfolio']")
         explore_Investment_Ideas_button.click()
         #In next screen click on button “Customize Portfolio” to make changes to portfolio
         customize_Portfolio_button= driver.find_element_by_xpath("//*[contains(text(),'Customize Portfolio') and @href = 'explore_portfolio/1']")
         customize_Portfolio_button.click()
         #Click on “Customize” button to enable edit controls
         customize_button= driver.find_element_by_xpath("//*[contains(text(),'Customise')]")
         customize_button.click()
         #Change slider of “ SPDR S&P 500 ETF TRUST SPY US EQUITY ” to 50%
         actions = ActionChains(driver)
         slider = driver.find_element_by_xpath("//*[@class='col-md-9']//child::input[1]")
         slider.location_once_scrolled_into_view
         driver.execute_script("window.scrollBy(0,200);")
         for i in range(0,100):
             actions.click_and_hold(slider).move_by_offset(i, 0).release().perform()
             slider_range = driver.find_element_by_xpath("//*[@class='col-md-9']//parent::div/div").text
             arr = list(re.split("%", slider_range))
             if arr[0] == "50":
                 print("PASS::slider of ' SPDR S&P 500 ETF TRUST SPY US EQUITY ' changed to 50%")
                 break
         #Click on “Rebalance” button
         rebalance_button= driver.find_element_by_xpath("//*[contains(text(),'Rebalance')]")
         rebalance_button.click()
         #Click on “Invest” button
         Invest_button = driver.find_element_by_xpath("//*[contains(text(),'Invest Now')]")
         Invest_button.click()
         #On next page” verify that “SPDR…” under “What your portfolio contain ?” to be 50%
         # As per testcase “SPDR…” under “What your portfolio contain ?” to be 50% but it is 13.79% hence verfiying that
         # On next page” verify that “SPDR…” under “What your portfolio contain ?” to be 50%
         spdr_percentage = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//ul[@class='list-group constituent-list clearfix']//li//following::span[2]")))
         spdr_percentage_txt = spdr_percentage.text
         if spdr_percentage_txt == "13.79":
                 print("PASS::“'SPDR…' under 'What your portfolio contain ?' to be 13.79%")
         else:
             print("FAIL::'SPDR…' under 'What your portfolio contain ?' is not as 13.79%")
     except:
         print_stack()
     finally:
         driver.quit()
Exemple #49
0
 def price_filter(self):
     price_filter = self.driver.find_element(
         *experiencesPageLocators.PRICE_FILTER)
     price_filter.click()
     act = ActionChains(self.driver)
     sliderleft = self.driver.find_element(
         *experiencesPageLocators.LEFT_SLIDER)
     act.click_and_hold(sliderleft).move_by_offset(40,
                                                   0).release().perform()
     time.sleep(4)
     sliderright = self.driver.find_element(
         *experiencesPageLocators.RIGHT_SLIDER)
     act.click_and_hold(sliderright).move_by_offset(-120,
                                                    0).release().perform()
     save_price = self.driver.find_element(
         *experiencesPageLocators.SAVE_PRICE)
     save_price.click()
Exemple #50
0
 def drag_element_at_position(self,
                              element: WebElement,
                              x: int,
                              y: int,
                              dx: int,
                              dy: int,
                              mod: _KeySeq | None = None) -> None:
     actions = ActionChains(self._driver)
     if mod:
         actions.key_down(mod)
     actions.move_to_element_with_offset(element, x, y)
     actions.click_and_hold()
     actions.move_by_offset(dx, dy)
     actions.release()
     if mod:
         actions.key_up(mod)
     actions.perform()
Exemple #51
0
 def solve_captcha(s):
     """this works (2018.10.14) but copy pasted from trial code. needs some refactoring
     to fit class structure and references"""
     while True:
         try:
             # 定位滑块元素,如果不存在,则跳出循环
             show = s.driver.find_element_by_xpath("//*[@id='nocaptcha']")
             if not show.is_displayed():
                 break
             source = s.driver.find_element_by_xpath("//*[@id='nc_1_n1z']")
             s.driver.implicitly_wait(3)
             # 定义鼠标拖放动作
             # ActionChains(driver).drag_and_drop_by_offset(source,400,0).perform()
             # driver.save_screenshot('login-screeshot-11.png')
         except:
             pass
         action = ActionChains(s.driver)
         s.driver.implicitly_wait(1)
         action.click_and_hold(source).perform()
         for index in range(10):
             try:
                 action.move_by_offset(4, 0).perform()  # 平行移动鼠标
                 # driver.save_screenshot('login-screeshot-i-'+str(index)+'.png')
             except Exception as e:
                 print(e)
                 break
             if index == 9:
                 action.release()
                 s.driver.implicitly_wait(0.05)
                 # s.driver.save_screenshot(os.path.join(Paths.img_path, 'screen_{}.png'.format(
                 #     datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))))
             else:
                 s.driver.implicitly_wait(0.01)  # 等待停顿时间
             s.driver.implicitly_wait(.5)
             # s.driver.save_screenshot(
             #     os.path.join(Paths.img_path, 'screen_{}.png'.format(datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))))
             text = s.driver.find_element_by_xpath(
                 "//*[@id='nc_1__scale_text']/span")
             if text.text.startswith(u'验证通过'):
                 print('成功滑动')
                 break
             if text.text.startswith(u'请点击'):
                 print('成功滑动')
                 break
             if text.text.startswith(u'请按住'):
                 continue
Exemple #52
0
    def login(self):
        self.driver.get(self.start_url)
        self.driver.implicitly_wait(10)
        self.driver.save_screenshot('tmp_login1.png')
        self.driver.find_element_by_class_name('J_UserName').clear()
        self.driver.find_element_by_css_selector(
            'span#J_StandardPwd input').clear()
        self.driver.find_element_by_class_name('J_UserName').send_keys(
            username)
        # time.sleep(2)
        self.driver.find_element_by_css_selector(
            'span#J_StandardPwd input').send_keys(pwd)
        # time.sleep(2)
        self.driver.find_element_by_css_selector('button.J_Submit').click()
        # time.sleep(4)
        print('正在拖动滑块进行验证...请稍等')
        # 获取滑动滑块的标签元素
        dragger = self.driver.find_element_by_class_name('nc-lang-cnt')
        action = ActionChains(self.driver)
        action.click_and_hold(dragger).perform()  # 鼠标左键按下不放

        # sleep(3)
        # self.driver.find_element_by_css_selector('span#J_StandardPwd input').send_keys(pwd)

        # for index in range(2000):
        try:
            # random_number = randint(1, 5)
            action.move_by_offset(300, 0).perform()  # 平行移动鼠标
        except UnexpectedAlertPresentException as e:
            print(e)
            # action.reset_actions()
            # sleep(0.02)  # 等待停顿时间
        action.click_and_hold(dragger).perform()  # 鼠标左键按下不放
        sleep(3)
        # # 重新赋值设置
        # self.driver.find_element_by_class_name('J_UserName').clear()
        # self.driver.find_element_by_css_selector('span#J_StandardPwd input').clear()
        # self.driver.find_element_by_class_name('J_UserName').send_keys(username)
        # # time.sleep(2)
        # self.driver.find_element_by_css_selector('span#J_StandardPwd input').send_keys(pwd)
        # # time.sleep(2)
        # self.driver.find_element_by_css_selector('button.J_Submit').click()
        sleep(4)
        # self.driver.implicitly_wait(10)
        self.driver.save_screenshot('tmp_login2.png')
Exemple #53
0
class TestHomepage():
    def __init__(self):
        self.browser = webdriver.Firefox()
        self.testTitle()

    def errorHandling(self, errorMsg):
        print errorMsg
        try:
            self.browser.close()
        except:
            pass
        exit(0)

    def testTitle(self):
        self.form_page = "http://demoqa.com/droppable"
        try:
            self.browser.get(self.form_page)
            self.drag = self.browser.find_elements_by_class_name(
                "ui-draggable")
            self.drop_reject = self.browser.find_element_by_id(
                "droppableaccept")
        except NoSuchElementException as e:
            self.errorHandling(e)
        except Exception as e:
            self.errorHandling(e)

        for i in self.drag:
            try:
                self.acn = ActionChains(self.browser)
                self.acn.click_and_hold(i)
                self.acn.move_to_element(self.drop)
                self.acn.click()
                self.acn.perform()
            except Exception as e:
                self.errorHandling(e)

            try:
                if self.drop.text == "Dropped!":
                    errorHandling("Well Done...!")
                    break

                else:
                    print "Do it again"
            except Exception as e:
                errorHanding(e)
Exemple #54
0
def pic_verify(br, xoff):
    actions = ActionChains(br)
    bar = br.find_element_by_class_name('dvc-slider__handler')
    actions.move_to_element(bar)
    actions.click_and_hold(bar)
    #     xoff = 175
    #     xoff = xoff+5 if xoff>250 else xoff
    xoff = xoff
    add_action(actions, xoff)  #xoff/480*280)
    actions.release()
    actions.perform()
    time.sleep(2)
    if '安全认证' not in br.page_source or '验证通过' in br.page_source:
        #print('验证成功')
        return 1
    else:
        #print('验证失败')
        return 0
Exemple #55
0
    def drag(self, source_index, target_index):
        """
        Gets the drag handle with index source_index (relative to the vertical layout of the page)
        and drags it to the location of the drag handle with target_index.

        This should drag the element with the source_index drag handle BEFORE the
        one with the target_index drag handle.
        """
        draggables = self.q(css='.drag-handle')
        source = draggables[source_index]
        target = draggables[target_index]
        action = ActionChains(self.browser)
        # When dragging before the target element, must take into account that the placeholder
        # will appear in the place where the target used to be.
        placeholder_height = 40
        action.click_and_hold(source).move_to_element_with_offset(
            target, 0, placeholder_height).release().perform()
        wait_for_notification(self)
Exemple #56
0
    def drag_and_drop(self, x_offset=0, y_offset=0, element_class="gt_slider_knob",falg=False):
        """拖拽滑块

        :x_offset: 相对滑块x坐标偏移
        :y_offset: 相对滑块y坐标偏移
        :element_class: 滑块网页元素CSS类名

        """
        #self.driver.save_screenshot("1.png")
        dragger = self.driver.find_element_by_class_name(element_class)
        action = ActionChains(self.driver)
        print(x_offset, y_offset)
        if not falg:
            action.drag_and_drop_by_offset(dragger, x_offset, y_offset).perform()
        else:
            # 生成x的移动轨迹点
            track_list = self.get_track(x_offset)
            # 获得滑动圆球的高度
            y = dragger.location['y']
            # 鼠标点击元素并按住不放
            print("第一步,点击元素")
            action.click_and_hold(dragger).perform()
            time.sleep(0.15)
            print("第二步,拖动元素")
            track_string = ""
            count=0
            for track in track_list:
                count=count+track
                #track_string = track_string + "{%d,%d}," % (track, y)
                #self.driver.save_screenshot("move%s.png" % count)
                action.move_by_offset(track,yoffset=0).perform()
                action.reset_actions()
                # 间隔时间也通过随机函数来获得,间隔不能太快,否则会被认为是程序执行
                ti=random.randint(10, 30-track) / 100
                time.sleep(ti)
                print(ti)

            print(track_string)
            print("第三步,释放鼠标")
            # 释放鼠标
            action.release().perform()
            time.sleep(0.5)
            self.driver.save_screenshot("okkkk%s.png" % uuid.uuid4())
        time.sleep(0.5)
Exemple #57
0
def drag(page, source_index, target_index, placeholder_height=0):
    """
    Gets the drag handle with index source_index (relative to the vertical layout of the page)
    and drags it to the location of the drag handle with target_index.

    This should drag the element with the source_index drag handle BEFORE the
    one with the target_index drag handle.
    """
    draggables = page.q(css='.drag-handle')
    source = draggables[source_index]
    target = draggables[target_index]
    action = ActionChains(page.browser)
    action.click_and_hold(source).move_to_element_with_offset(
        target, 0, placeholder_height)
    if placeholder_height == 0:
        action.release(target).perform()
    else:
        action.release().perform()
    wait_for_notification(page)
Exemple #58
0
def drag_slider(driver):
    slider = driver.find_element_by_id('nc_2_n1z')
    slider.click()
    ac = ActionChains(driver)
    ac.move_to_element(slider)
    ac.click_and_hold(slider)
    xoffset = 0
    while xoffset < 350:
        xmove = random.randint(10, 40)
        ymove = random.randint(-1, 1)
        ac.move_by_offset(xmove, ymove)
        xoffset += xmove
    ac.release()
    ac.perform()

    time.sleep(3)

    element = driver.find_element_by_class_name('nc-lang-cnt')
    print(element.text)
Exemple #59
0
 def simuMove(self, slider, track):
     act = AC(self.driver)
     onElem = act.click_and_hold(slider).perform()
     for x in track:
         print(x)
         act.move_by_offset(x, 0).perform()
         act = AC(self.driver)
         sleep(.3)
     sleep(.5)
     act.release().perform()
Exemple #60
0
 def cook_songlist_page(self, index=None):
     if index is None:
         self.driver.get(self.baseurl)
     else:
         self.driver.get(f'{self.baseurl}/?page={index+1}')
     ranked = self.driver.find_element_by_xpath("//input[@id='ranked']")
     if self.unranked:
         if ranked.is_selected() is True:
             ranked.click()  # disable ranked option
     else:
         if ranked.is_selected() is not True:
             ranked.click()  # Enalbe ranked option
     cats = self.driver.find_element_by_xpath("//select[@id='cats']")
     cats = Select(cats)
     cats.select_by_visible_text("Date Ranked")
     time.sleep(5)
     self.driver.find_element_by_xpath(
         ".//input[@type='radio' and @id='asc']").click()
     maxstar = self.driver.find_element_by_xpath(
         "//input[@id='sliderWithValue']")
     # maxstar.send_keys("50")
     starmove = ActionChains(self.driver)
     starmove.click_and_hold(maxstar).move_by_offset(300,
                                                     0).release().perform()
     update_button = self.driver.find_element_by_xpath(
         "//button[@onclick='onToggle2()']")
     update_button.click()
     time.sleep(5)
     soup = None
     counter = 0
     while soup is None and counter < self.maxretry:
         soup = BeautifulSoup(self.driver.page_source, 'html.parser')
         time.sleep(self.intervalf())
         counter += 1
         try:
             links = self.extract_links(soup)
             leaderboards = self.find_leaderborads(links)
             if len(leaderboards) == 0:
                 soup = None
                 leaderboards = None
         except:
             soup = None
     return links, leaderboards