user2405920
user2405920

Reputation: 69

Get text of css element selenium

I am trying to use selenium to access the text of a css element.

WebElement test = driver.findElement(By.cssSelector("div.CLFSBTextWithLink"));
System.out.println(test.getText());

This is what I'm doing right now but the output is empty.

For example the there might be a link or text on a website called "Company" and when I use Selenium to check where the element is, it says that the target is css=div.CLFSBTextWithLink. Now I want to be able to get the value "Company" somehow.

Upvotes: 0

Views: 2933

Answers (1)

Petr Janeček
Petr Janeček

Reputation: 38424

If you go to http://viewer.opencalais.com/ and type something like "There was a man named Bob Bob" and hit submit, then you see under the entity person the name Bob Bob. I'm trying to get that name "Bob Bob" basically.


From the getText() docs:

Get the visible (i.e. not hidden by CSS) innerText of this element

But the text is initially hidden. You must first expand the Person element to make it visible. In this particular "Bob Bob" case, you can use:

driver.findElement(By.id("toggleVisibilityImage1")).click();

But always make sure you're clicking the right expander. To make it more general, this selects the expander next to the "Person" category:

//input[@class='collapseExpandIcon' and (../text()='Person')]

and explanation:

SELECT AN <input> ELEMENT
//input[                                                    ]
        THAT IS AN EXPANDER
        @class='collapseExpandIcon'
                                    AND ITS PARENT NODE HAS TEXT "Person"
                                    and (../text()='Person')

Upvotes: 2

Related Questions