0

This is a continuation from my other post

Using JSoup to get data-code value of a table

I am trying to get the text inside the <span> tags on the table using the cssSelector() method in Selenium webdriver

<table class ="team-list">
          <tr data-code="1">
              <td>
              <span>
                 Get This Text
              </span>
              </td>     
          </tr>
  </table>

I have tried the following code, but this will print out the text in all cells for each row, but i only need to get the one inside the <span> tags

WebDriver driver = new FirefoxDriver();
driver.get("http://www.example.com");

List<WebElement> elements = driver.findElements(By.cssSelector("table.team-list td"));

for(WebElement element: elements)
{
    System.out.println(element.getText());
}
2
  • use .team-list td span ... u r providing td so it will give text of all tds including those which don't have span also. Commented Feb 20, 2015 at 20:26
  • This worked for me List<WebElement> elements = driver.findElements(By.cssSelector("table.team-list td > td:nth-of-type(2)")); Commented Feb 20, 2015 at 21:29

3 Answers 3

1

if you know the text you are looking for you can the following:

WebDriver driver = new FirefoxDriver();
driver.get("http://www.example.com");

List<WebElement> elements = driver.findElements(By.cssSelector("table.team-list td"));

for(WebElement element: elements)
{
    if(element.getText().equals("Get This Text"))
       System.out.println(element.getText());
}

That's might be o(n) but if you are not care about performance that could solve your problem.

Sign up to request clarification or add additional context in comments.

Comments

0

I think you should change your selector to this:

By.cssSelector("table.team-list span")

Comments

0

Try something like this.

WebDriver driver = new FirefoxDriver();
driver.get("http://www.example.com");
List<WebElement> elements = driver.findElements(By.cssSelector("table.team-list td"));

    for(WebElement element: elements)
    {
        try{
           System.out.println(element.findElement(By.tagName("span")).getText());
         }(org.openqa.selenium.NoSuchElementException nsee){
         }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.