Log in
updated 11:29 AM UTC, May 4, 2016

Finding webelement by its associated label using Selenium

  • Written by Madhu V Rao
  • Published in Automation

Find a HTML element (input/select or textarea) using the associated label using Selenium

	public WebElement byLabel(int occurance,String label) {
		if(occurance <=0) occurance = 1;
		WebElement first = null;
		int position = 1;
		List<WebElement> wes = we.findElements(By
				.xpath("//label[normalize-space()='" + label + "']"));
		for (WebElement we : wes) {
			if (we.isDisplayed()) {
				if (position == occurance) {
					if(Config.DEBUG) {
						System.out.println("[DEBUG] Found " + occurance + " element by label: " + label);
					}
					first = we;
					break;
				} else {
					position++;
				}

			}
		}
		if (first == null)
			throw new IllegalArgumentException("no label with text=" + label);
		String f = first.getAttribute("for");
		if (f == null)
			throw new IllegalArgumentException("for == null");
		WebElement we2 = we.findElement(By.id(f));
		if (we2 == null)
			throw new IllegalArgumentException("no element for id: " + f);
		return we2;
	}


Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest