Java Code Examples for org.openqa.selenium.support.ui.Select#selectByIndex()

The following examples show how to use org.openqa.selenium.support.ui.Select#selectByIndex() . 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 check out the related API usage on the sidebar.
Example 1
Source File: SeleniumSelect.java    From phoenix.webui.framework with Apache License 2.0 6 votes vote down vote up
@Override
public WebElement randomSelect(Element ele)
{
	Select select = createSelect(ele);
	if(select != null)
	{
		List<WebElement> options = select.getOptions();
		if(CollectionUtils.isNotEmpty(options))
		{
			int count = options.size();
			int index = RandomUtils.nextInt(count);
			index = (index == 0 ? 1 : index); //通常第一个选项都是无效的选项

			select.selectByIndex(index);
			
			return options.get(index);
		}
	}
	
	return null;
}
 
Example 2
Source File: FieldActions.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
public void selectItemInDropDownList(Select select, String text, boolean addition)
{
    if (select != null)
    {
        boolean multiple = select.isMultiple();
        if (!multiple && addition)
        {
            softAssert
                    .recordFailedAssertion("Multiple selecting is not available to single select drop down");
            return;
        }
        boolean selected = false;
        List<WebElement> options = select.getOptions();
        for (int i = 0; i < options.size(); i++)
        {
            WebElement currentOption = options.get(i);
            String optionValue = webElementActions.getElementText(currentOption).trim();
            if (text.equals(optionValue))
            {
                select.selectByIndex(i);
                selected = true;
                if (!multiple)
                {
                    break;
                }
            }
            else if (currentOption.isSelected() && !addition && multiple)
            {
                select.deselectByIndex(i);
            }
        }
        String assertionMessage = multiple ? String.format(
                "Items with the text '%s' are selected from a drop down", text) : String.format(
                "Item with the text '%s' is selected from a drop down", text);
        softAssert.assertTrue(assertionMessage, selected);
        waitActions.waitForPageLoad();
    }
}
 
Example 3
Source File: EncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String selectOperation(WebElement we, String operation, String operationValue) {
    String result = "";
    // �����������
    Select select = new Select(we);

    // �����������¼�
    switch (operation) {
        case "selectbyvisibletext":
            select.selectByVisibleText(operationValue);
            result = "���������ͨ��VisibleText����ѡ��...��VisibleText����ֵ:" + operationValue + "��";
            LogUtil.APP.info("���������ͨ��VisibleText����ѡ��...��VisibleText����ֵ:{}��",operationValue);
            break;
        case "selectbyvalue":
            select.selectByValue(operationValue);
            result = "���������ͨ��Value����ѡ��...��Value����ֵ:" + operationValue + "��";
            LogUtil.APP.info("���������ͨ��Value����ѡ��...��Value����ֵ:{}��",operationValue);
            break;
        case "selectbyindex":
            select.selectByIndex(Integer.parseInt(operationValue));
            result = "���������ͨ��Index����ѡ��...��Index����ֵ:" + operationValue + "��";
            LogUtil.APP.info("���������ͨ��Index����ѡ��...��Index����ֵ:{}��",operationValue);
            break;
        case "isselect":
            result = "��ȡ����ֵ�ǡ�" + we.isSelected() + "��";
            LogUtil.APP.info("�ж϶����Ƿ��Ѿ���ѡ��...�����ֵ:{}��",we.isSelected());
            break;
        default:
            break;
    }
    return result;
}
 
Example 4
Source File: IosEncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String selectOperation(IOSElement ie, String operation, String operationValue) {
	String result = "";
	// �����������
	Select select = new Select(ie);

	// �����������¼�
	switch (operation) {
	case "selectbyvisibletext":
		select.selectByVisibleText(operationValue);
		LogUtil.APP
				.info("���������ͨ��VisibleText����ѡ��...��VisibleText����ֵ:{}��",operationValue);
		break;
	case "selectbyvalue":
		select.selectByValue(operationValue);
		LogUtil.APP.info("���������ͨ��Value����ѡ��...��Value����ֵ:{}��",operationValue);
		break;
	case "selectbyindex":
		select.selectByIndex(Integer.parseInt(operationValue));
		LogUtil.APP.info("���������ͨ��Index����ѡ��...��Index����ֵ:{}��",operationValue);
		break;
	case "isselect":
		result = "��ȡ����ֵ�ǡ�" + ie.isSelected() + "��";
		LogUtil.APP.info("�ж϶����Ƿ��Ѿ���ѡ��...�����ֵ:{}��",ie.isSelected());
		break;
	default:
		break;
	}
	return result;
}
 
Example 5
Source File: AndroidEncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * select�ؼ��ؼ��ִ���
 * @param ae UI����
 * @param operation �����ؼ���
 * @param operationValue ����ֵ
 * @return ���ز������
 */
public static String selectOperation(AndroidElement ae, String operation, String operationValue) {
	String result = "";
	// �����������
	Select select = new Select(ae);

	// �����������¼�
	switch (operation) {
	case "selectbyvisibletext":
		select.selectByVisibleText(operationValue);
		LogUtil.APP
				.info("���������ͨ��VisibleText����ѡ��...��VisibleText����ֵ:{}��",operationValue);
		break;
	case "selectbyvalue":
		select.selectByValue(operationValue);
		LogUtil.APP.info("���������ͨ��Value����ѡ��...��Value����ֵ:{}��",operationValue);
		break;
	case "selectbyindex":
		select.selectByIndex(Integer.parseInt(operationValue));
		LogUtil.APP.info("���������ͨ��Index����ѡ��...��Index����ֵ:{}��",operationValue);
		break;
	case "isselect":
		result = "��ȡ����ֵ�ǡ�" + ae.isSelected() + "��";
		LogUtil.APP.info("�ж϶����Ƿ��Ѿ���ѡ��...�����ֵ:{}��",ae.isSelected());
		break;
	default:
		break;
	}
	return result;
}
 
Example 6
Source File: SeleniumSelect.java    From phoenix.webui.framework with Apache License 2.0 5 votes vote down vote up
@Override
public boolean selectByIndex(Element element, int index)
{
	Select select = createSelect(element);
	if(select != null)
	{
		select.selectByIndex(index);
		return true;
	}

	return false;
}
 
Example 7
Source File: Step.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void setDropDownValue(PageElement element, String text, Object... args) throws TechnicalException, FailureException {
    final WebElement select = Wait.until(ExpectedConditions.elementToBeClickable(Utilities.getLocator(element, args)));
    final Select dropDown = new Select(select);
    final int index = userNameService.findOptionByIgnoreCaseText(text, dropDown);
    if (index != -1) {
        dropDown.selectByIndex(index);
    } else {
        new Result.Failure<>(text.startsWith(cryptoService.getPrefix()) ? SECURE_MASK : text,
                Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_VALUE_NOT_AVAILABLE_IN_THE_LIST), element, element.getPage().getApplication()), false, element.getPage().getCallBack());
    }
}
 
Example 8
Source File: SelectListOption.java    From opentest with MIT License 5 votes vote down vote up
@Override
public void run() {
    super.run();

    By locator = this.readLocatorArgument("locator");
    String optionValue = this.readStringArgument("optionValue", null);
    String optionText = this.readStringArgument("optionText", null);
    Integer optionNumber = this.readIntArgument("optionNumber", null);

    this.waitForAsyncCallsToFinish();

    Select dropdownElement = new Select(this.getElement(locator));

    if (optionValue != null) {
        dropdownElement.selectByValue(optionValue);
    } else if (optionText != null) {
        dropdownElement.selectByVisibleText(optionText);
    } else if (optionNumber != null) {
        dropdownElement.selectByIndex(optionNumber - 1);
    } else {
        throw new RuntimeException(
                "You must identify the option you want to select from the "
                + "list by providing one of the following arguments: "
                + "optionValue, optionText or optionNumber.");
    }

}
 
Example 9
Source File: Dropdown.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
private void selectAll(SelectType selectType) {
    switch (selectType) {
        case Select:
            Select select = new Select(Element);
            for (int i = 0; i < select.getOptions().size(); i++) {
                select.selectByIndex(i);
            }
            break;
        case DeSelect:
            new Select(Element).deselectAll();
            break;
    }

}
 
Example 10
Source File: DropDownListInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Выбор из выпадающего списка n-го элемента
 * (в приоритете: из property, из переменной сценария, значение аргумента)
 */
@Тогда("^выбран (\\d+)-й элемент в выпадающем списке \"([^\"]*)\"$")
@Then("^selected the (\\d+)(st|nd|rd|th) element from the drop down list named \"([^\"]*)\"$")
public void selectElementNumberFromDropDownList (int elementNumber, String listName) {
    Select list = new Select(akitaScenario.getCurrentPage().getElement(listName));
    Integer selectedElementNumber = elementNumber - 1;
    if (selectedElementNumber < 0 || selectedElementNumber >= list.getOptions().size()) {
        throw new IndexOutOfBoundsException(
                String.format("В списке %s нет элемента с номером %s. Количество элементов списка = %s",
                        listName, elementNumber, list.getOptions().size()));
    }
    list.selectByIndex(selectedElementNumber);
}
 
Example 11
Source File: DropDownStepDefinitions.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
/**
 * Select an item index from a drop down list using simple selection
 *
 * @param itemAlias     If this word is found in the step, it means the itemName is found from the data
 *                      set.
 * @param itemIndex     The index of the item to select
 * @param alias         If this word is found in the step, it means the selectorValue is found from the
 *                      data set.
 * @param selectorValue The value used in conjunction with the selector to match the element. If alias was
 *                      set, this value is found from the data set. Otherwise it is a literal value.
 * @param exists        If this text is set, an error that would be thrown because the element was not
 *                      found is ignored. Essentially setting this text makes this an optional statement.
 */
@When("^I select option(?: number)?( alias)? \"([^\"]*)\" from (?:a|the)(?: drop down list found by)?"
	+ "( alias)? \"([^\"]*)\"(?: \\w+)*?( if it exists)?$")
public void selectSimpleDropDownListIndexStep(
	final String itemAlias,
	final String itemIndex,
	final String alias,
	final String selectorValue,
	final String exists) {
	try {
		final String selection = autoAliasUtils.getValue(
			itemIndex, StringUtils.isNotBlank(itemAlias), State.getFeatureStateForThread());

		checkState(selection != null, "the aliased item index does not exist");

		final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();

		final WebElement element = simpleWebElementInteraction.getClickableElementFoundBy(
			StringUtils.isNotBlank(alias),
			selectorValue,
			State.getFeatureStateForThread());

		mouseMovementUtils.mouseGlide(
			webDriver,
			(JavascriptExecutor) webDriver,
			element,
			Constants.MOUSE_MOVE_TIME,
			Constants.MOUSE_MOVE_STEPS);

		final Select select = new Select(element);
		select.selectByIndex(Integer.parseInt(selection));
		sleepUtils.sleep(State.getFeatureStateForThread().getDefaultSleep());
	} catch (final WebElementException ex) {
		if (StringUtils.isBlank(exists)) {
			throw ex;
		}
	}
}
 
Example 12
Source File: QueueSubscriptionsPage.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Search queue subscriptions according to the search criteria.
 *
 * @param queueNamePattern string pattern of the queue name (* for all)
 * @param identifierPattern string pattern of the identifier (* for all)
 * @param ownNodeIdIndex index of the node Id in the dropdown the subscriptions belong to
 * @return number of subscriptions listed under search result
 */
public int searchQueueSubscriptions(String queueNamePattern, String identifierPattern, int ownNodeIdIndex,
                                    boolean isNameExactMatch, boolean isIdentifierExactMatch) {

    WebElement queueNamePatternField = driver.findElement(By.name(UIElementMapper.getInstance()
            .getElement("mb.search.queue.name.pattern.tag.name")));
    queueNamePatternField.clear();
    queueNamePatternField.sendKeys(queueNamePattern);

    WebElement queueNameExactMatchField = driver.findElement(
            By.name(UIElementMapper.getInstance().getElement("mb.search.queue.name.exactmatch.tag.name")));
    // Set the name exact match check box state based on the test input
    if (isNameExactMatch != queueNameExactMatchField.isSelected()) {
        queueNameExactMatchField.click();
    }
    WebElement queueIdentifierExactMatchField = driver.findElement(
            By.name(UIElementMapper.getInstance().getElement("mb.search.queue.identifier.exactmatch.tag.name")));
    // Set the identifier exact match check box state based on the test input
    if (isIdentifierExactMatch != queueIdentifierExactMatchField.isSelected()) {
        queueIdentifierExactMatchField.click();
    }

    WebElement queueIdentifierPatternField = driver.findElement(By.name(UIElementMapper.getInstance()
            .getElement("mb.search.queue.identifier.pattern.tag.name")));
    queueIdentifierPatternField.clear();
    queueIdentifierPatternField.sendKeys(identifierPattern);

    Select ownNodeIdDropdown = new Select(driver.findElement(By.id(UIElementMapper.getInstance()
            .getElement("mb.search.queue.own.node.id.element.id"))));
    ownNodeIdDropdown.selectByIndex(ownNodeIdIndex);

    driver.findElement(By.xpath(UIElementMapper.getInstance()
            .getElement("mb.search.queue.search.button.xpath"))).click();

    return getSubscriptionCount();

}
 
Example 13
Source File: TopicSubscriptionsPage.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Search topic subscriptions according to the search criteria.
 *
 * @param queueNamePattern string pattern of the topic name (* for all)
 * @param identifierPattern string pattern of the identifier (* for all)
 * @param ownNodeIdIndex index of the node Id in the dropdown the subscriptions belong to
 * @return number of subscriptions listed under search result
 */
public void searchTopicSubscriptions(String queueNamePattern, String identifierPattern, int
        ownNodeIdIndex, boolean isNameExactMatch, boolean isIdentifierExactMatch) {

    WebElement queueNamePatternField = driver.findElement(By.name(UIElementMapper.getInstance()
            .getElement("mb.search.topic.name.pattern.tag.name")));
    queueNamePatternField.clear();
    queueNamePatternField.sendKeys(queueNamePattern);

    WebElement queueIdentifierPatternField = driver.findElement(By.name(UIElementMapper.getInstance()
            .getElement("mb.search.topic.identifier.pattern.tag.name")));
    queueIdentifierPatternField.clear();
    queueIdentifierPatternField.sendKeys(identifierPattern);

    WebElement topicNameExactMatchField = driver.findElement(
            By.name(UIElementMapper.getInstance().getElement("mb.search.topic.name.exactmatch.tag.name")));
    // Set the name exact match check box state based on the test input
    if (isNameExactMatch != topicNameExactMatchField.isSelected()) {
        topicNameExactMatchField.click();
    }
    WebElement topicIdentifierExactMatchField = driver.findElement(
            By.name(UIElementMapper.getInstance().getElement("mb.search.topic.identifier.exactmatch.tag.name")));
    // Set the identifier exact match check box state based on the test input
    if (isIdentifierExactMatch != topicIdentifierExactMatchField.isSelected()) {
        topicIdentifierExactMatchField.click();
    }

    Select ownNodeIdDropdown = new Select(driver.findElement(By.id(UIElementMapper.getInstance()
            .getElement("mb.search.topic.own.node.id.element.id"))));
    ownNodeIdDropdown.selectByIndex(ownNodeIdIndex);

    driver.findElement(By.xpath(UIElementMapper.getInstance()
            .getElement("mb.search.topic.search.button.xpath"))).click();

}
 
Example 14
Source File: DropDownStepDefinitions.java    From IridiumApplicationTesting with MIT License 4 votes vote down vote up
/**
 * Select an item index from a drop down list
 *
 * @param itemAlias     If this word is found in the step, it means the itemName is found from the data
 *                      set.
 * @param itemIndex     The index of the item to select
 * @param selector      Either ID, class, xpath, name or css selector
 * @param alias         If this word is found in the step, it means the selectorValue is found from the
 *                      data set.
 * @param selectorValue The value used in conjunction with the selector to match the element. If alias was
 *                      set, this value is found from the data set. Otherwise it is a literal value.
 * @param exists        If this text is set, an error that would be thrown because the element was not
 *                      found is ignored. Essentially setting this text makes this an optional statement.
 */
@When("^I select option(?: number)?( alias)? \"([^\"]*)\" from (?:a|the) drop down list with (?:a|an|the) "
	+ "(ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\"( if it exists)?$")
public void selectDropDownListIndexStep(
	final String itemAlias,
	final String itemIndex,
	final String selector,
	final String alias,
	final String selectorValue,
	final String exists) {
	try {
		final String selection = autoAliasUtils.getValue(
			itemIndex, StringUtils.isNotBlank(itemAlias), State.getFeatureStateForThread());

		checkState(selection != null, "the aliased item index does not exist");

		final By by = getBy.getBy(
			selector,
			StringUtils.isNotBlank(alias),
			selectorValue,
			State.getFeatureStateForThread());
		final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
		final WebDriverWait wait = new WebDriverWait(
			webDriver,
			State.getFeatureStateForThread().getDefaultWait(),
			Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
		final WebElement element = wait.until(ExpectedConditions.elementToBeClickable(by));

		mouseMovementUtils.mouseGlide(
			webDriver,
			(JavascriptExecutor) webDriver,
			element,
			Constants.MOUSE_MOVE_TIME,
			Constants.MOUSE_MOVE_STEPS);

		final Select select = new Select(element);
		select.selectByIndex(Integer.parseInt(selection));
		sleepUtils.sleep(State.getFeatureStateForThread().getDefaultSleep());
	} catch (final TimeoutException | NoSuchElementException ex) {
		if (StringUtils.isBlank(exists)) {
			throw ex;
		}
	}
}
 
Example 15
Source File: DropDownHelper.java    From SeleniumCucumber with GNU General Public License v3.0 4 votes vote down vote up
public void SelectUsingIndex(By locator,int index) {
	Select select = new Select(getElement(locator));
	select.selectByIndex(index);
	oLog.info("Locator : " + locator + " Index : " + index);
}