How to locate a span with a specific text in Selenium? (Using Java)

100,000

Solution 1

Your all xpath are looks OK, Just some syntactically incorrect. you are missing // in your xpath

The correct xpath are as below :-

By by = By.xpath("//span[.='Settings']")

Or

By by = By.xpath("//span[text()='Settings']")

Or

By by = By.xpath("//div[@class='settings-padding']/span"))

Or you can use cssSelector as :-

By by = By.cssSelector("div.settings-padding > span"))

Using anyone of the above By locator you can locate element as below :-

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement el = wait.until(presenceOfElementLocated(by));

Hope it helps...:)

Solution 2

For the element below

<span class="test-button__text">
    Test Text
</span>

The following solution works for me

driver.find_element_by_xpath("//span[contains(@class, 'test-button__text') and text()='Test Text']")
Share:
100,000
HosseinK
Author by

HosseinK

Updated on May 23, 2020

Comments

  • HosseinK
    HosseinK almost 4 years

    I'm having trouble locating a span element in Selenium using java.

    the HTML looks like:

    <div class="settings-padding">
    <span>Settings</span>
    </div>

    And I've tried the following with no luck:

    By.xpath("span[.='Settings']")
    

    and

    By.xpath("span[text()='Settings']")
    

    and

    By.cssSelector("div[class='settings-padding']"))
    

    as well as some other similar attempts. Could you point me to the best method to do this? As it stands I constantly get "Unable to locate element" error in eclipse.