Stas Mackarow
Stas Mackarow

Reputation: 195

How to get text from span class using Selenium ChromeDriver

I looked simillar questions at stackoverflow and didn't find anything that can help me.

I have following html code:

<span class="help-block ng-scope" translate="">Company</span>

How can i find this element (Java)? I tried following variants:

driver.findElement(By.cssSelector(".help-block.ng-scope"))

driver.findElement(By.xpath("//span[contains(@class, "Company")]"))

I even tried to just copy xpath from browser console in two ways:

First:

driver.findElement(By.xpath("//*[@id="ngCloudike"]/body/div[6]/div/div/div/div/form/div[1]/div[6]/span"))

Second:

driver.findElement(By.xpath("/html/body/div[6]/div/div/div/div/form/div[1]/div[6]/span"))

Also i tried to find By.ClassName, but i can't do this, because there are some spaces. So, how can i find element like this?

Upvotes: 3

Views: 1707

Answers (1)

Andersson
Andersson

Reputation: 52665

Try below expression:

driver.findElement(By.xpath("//span[text()='Company']"))

If you get NoSuchElementException with this code, try to add some time to wait until element present and visible:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()='Company']"))

If you get NoSuchElementException even with ExplicitWait, target element might be located inside an iframe. To handle element inside an iframe:

driver.switchTo().frame("iframeNameOrId");
driver.findElement(By.xpath("//span[text()='Company']"));

Upvotes: 1

Related Questions