Anderson
Anderson

Reputation: 33

How would I select this element using Selenium in Java?

I am trying to select for the value 1352 in Java Selenium on ChromeDriver

<span class="numfound" id="yui_3_18_1_1_1522936314968_15">1352</span>

Because the id is nonintuitive, I'd like to select using the String "numfound". I've tried selecting byClassName("numfound") and this was returned:

<[[ChromeDriver: chrome on MAC (befee42078624a3b036869cf2a4a0c14)] -> class name: numfound]>

Alternatively, I've tried to select by CSS and got this:

Unable to locate element: {"method":"css selector","selector":"#resultsnum span.numfound"}

Perhaps my selector for CSS was wrong? What would be the most intuitive way to select this element using numfound?

RESOLVED: I was silly and didn't use .getText() for what I wanted.

Upvotes: 1

Views: 87

Answers (3)

cruisepandey
cruisepandey

Reputation: 29362

This span is a WebElement. There are certain things that you can do with WebElement. Some of those are :

    1. click on it. (Provided that element must be clickable)
    2. getText() : Text between the <span> and </span> tag.
    3. getSize();
    4. getLocation();
    5. getScreenShotAs(OUTPUT.Type)
    6. getRect();
    7. SendKeys(charSequence)  (Provided that it can take input something).

and many more.

As of now, in your problem, you can get the text between span tag. by using this code :

String spanText = driver.findElement(by.cssSelector("span[class="numfound"]")).getText();  

and do String operations on it.
Let me know if you have any concerns about this.

Upvotes: 1

Margon
Margon

Reputation: 511

You just have to do:

WebElement element = browser.findElement(By.className("numfound"));
//do whatever you want with your element, get attributes, etc.

For reference: https://www.seleniumhq.org/docs/03_webdriver.jsp#by-class-name

Upvotes: 0

AcMuD
AcMuD

Reputation: 131

You can use the By-selector only for elements inside of the tag.

To get the text of an element

  1. you can use

    driver.findElement(By.xpath("//span[@class='numfound']")).getText();

    or (if you like more):

    driver.findElement(By.className("numfound")).getText();

  2. or get it from the page source by

    String source = driver.getPageSource();

and extract a string from this, starting with "numfound" and ending with following tag Then extract your string from this line.

Upvotes: 0

Related Questions