2013-11-27 4 views
1

Используя WebDriver и Junit 4.11, у меня есть элемент слайдера (изменяет непрозрачность компонента от 0 до 100%), который я хочу щелкнуть мышью, а затем отпустить в определенный момент ,WebDriver перетаскивает элемент в определенную целевую область

Я могу перетащить компоненты на целевую область, а затем изменить значение, найдя элементы текстового поля для оси x и y. Но в этом случае мне нужно автоматизировать слайдер. Возможно ли это?

HTML код ниже для слайдера:

<div class="inputWrapper"> <input type="range" value="1" name="opacity" id="c409" min="0" max="1" step="0.01" class="t-textInput-A"><span class="units">%</span><div class="sliderTooltip" style="display: none; margin-left: 97px;">100%</div> </div> 

Ползунок в настоящее время устанавливается на 100%, но как я могу захватить элемент и перетащить его, чтобы сказать, например, 10%?

Я взял скриншот, чтобы показать, что это я пытаюсь схватить: http://screencast.com/t/YjdoFtSG

Большое спасибо заранее.

ответ

0

Вы можете попробовать поэкспериментировать с этими функциями (я использую phpwebdriver)

/** 
    * Move the mouse by an offset of the specificed element. 
    * If no element is specified, the move is relative to the current mouse cursor. 
    * If an element is provided but no offset, the mouse will be moved to the center of the element. 
    * If the element is not visible, it will be scrolled into view. 
    * 
    * @param WebElement $element 
    * ID of the element to move to. If not specified or is null, 
    * the offset is relative to current position of the mouse. 
    * @param integer $xoffset 
    * X offset to move to, relative to the top-left corner of the element. 
    * If not specified, the mouse will move to the middle of the element. 
    * @param integer $yoffset 
    * Y offset to move to, relative to the top-left corner of the element. 
    * If not specified, the mouse will move to the middle of the element. 
    */ 
    public function moveTo($element = null, $xoffset = null, $yoffset = null) 
    { 
     $request = $this->requestURL . "/moveto"; 
     $session = $this->curlInit($request); 

     $array = explode('/', $element->requestURL);   
     $id = $array[count($array) - 1];   
     $args = array(); 
     if($element) $args['element'] = $id; 
     if($xoffset) $args['xoffset'] = intval($xoffset); 
     if($yoffset) $args['yoffset'] = intval($yoffset); 
     if(empty($args)) 
      $this->preparePOST($session, null); 
     else{ 
      $postargs = json_encode($args); 
      $this->preparePOST($session, $postargs); 
     } 
     curl_exec($session); 
    } 

    /** 
    * Click and hold the left mouse button (at the coordinates set by the last moveto command). 
    * Note that the next mouse-related command that should follow is buttonUp() . 
    * Any other mouse command (such as click() or another call to buttonDown()) will yield undefined behaviour. 
    * 
    * @param integer $button 
    * Which button, enum: {LEFT = 0, MIDDLE = 1 , RIGHT = 2}. 
    * Defaults to the left mouse button if not specified. 
    */ 
    public function buttonDown() 
    { 
     $request = $this->requestURL . "/buttondown"; 
     $session = $this->curlInit($request); 
     $this->preparePOST($session, null); 
     curl_exec($session); 
    } 
    /** 
    * Releases the mouse button previously held (where the mouse is currently at). 
    * Must be called once for every buttonDown() command issued. 
    * See the note in click and buttonDown() about implications of out-of-order commands. 
    * 
    * @param integer $button 
    * Which button, enum: {LEFT = 0, MIDDLE = 1 , RIGHT = 2}. 
    * Defaults to the left mouse button if not specified. 
    */ 
    public function buttonUp() 
    { 
     $request = $this->requestURL . "/buttonup"; 
     $session = $this->curlInit($request); 
     $this->preparePOST($session, null); 
     curl_exec($session); 
    } 

    /** 
    * Maximize the specified window if not already maximized. 
    * If the :windowHandle URL parameter is "current", the currently active window will be maximized. 
    */ 
0

В этом случае я вообще должен был упасть с помощью координат. Если вы используете Clickandhold я предполагаю, что вы нанизывание действия так для второго действия, сделайте следующее:

moveByOffset (-100, 0)

или любой правильного размером шага. Это переместит мышь из положения, в котором он находится сейчас (после щелчка мышью), оставленного на 100 пикселей, который должен перетащить ползунок.

+0

Спасибо за ваш ответ @stirno. Я знал об этой команде, хотя мне не удалось реализовать ее в своем тесте. Кажется, что код в моем вопросе выглядит серым, с # фрагментом документа перед div. Поэтому мне интересно, что это заблокировано, поэтому не позволяет мне автоматизировать ползунок? Я включил скриншот, который иллюстрирует серый код. http://screencast.com/t/zGUj64ZRS –

1

Это просто. Отправьте значение в поле и активируйте событие «change» в этом поле. В качестве примера выполнить этот скрипт в браузере:

arguments[0].valueAsNumber = arguments[1]; 
    var mEvent = document.createEvent("Event"); 
    mEvent.initEvent('change', true, true); 
    arguments[0].dispatchEvent(mEvent); 
  • argument[0] - тип входного = диапазон веб-элемент
  • argument[1] - нужен размер

Внимание, этот пример работы в Firefox и Chrome, но не работает в Internet Explorer. Прочтите документы об «fireEvent» в IE.

Смежные вопросы