0

I am quite new on Selenium (started today) and I would like to get the WebElement corresponding to the following html Input:

<input size="25" style="text-align:center;" value="http" onclick="this.select();" type="text"></input>

And then obtain its value. This is what I have tried so far:

WebElement element = driver.findElement(By.cssSelector(".text-align:center"));
String text = element.getText();

Or this:

WebElement element = driver.findElement(By.cssSelector("input[style='text-align:center']"));

But Java returns in both cases an exception:

org.openqa.selenium.InvalidSelectorException: The given selector .text-align:center is either invalid or does not result in a WebElement

Thank you, Héctor

2 Answers 2

2

Do you have to search for the element by cssSelector?

You could give this a try:

WebElement element = driver.findElement(By.cssSelector("input[type='text']"));

If cssSelector is not necessary you could try grabbing the element by xpath. If you use firefox, there is a plugin called FireBug which allows you to right click after inspecting the element and copying the xpath directly then using :

WebElement element = driver.findElement(By.xpath("XPATH HERE"));

EDIT: Part of post disappeared, redded it.

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

3 Comments

It worked with xpath! Thank you! On the other hand, when I do the following: referralBox.getAttribute("value") I don't get the value; but if I write referralBox.getAttribute("style") it returns the style. I don't get it, I guess it is because the page has more than one HTML input with the same type = 'text'.
Try using referralBox.getAttribute("innerHTML"); or using referralBox.getText();
Your CSS selector, input[type='text'], is not going to be specific enough unless it's the only INPUT on the page.
0

Your first try is slightly off

driver.findElement(By.cssSelector(".text-align:center"));

The (.) in a CSS selector indicates a CSS class name but that's a style on the element and not a class. There is no class on that element to use in that way.

Your second try looks good but maybe it's not unique on the page? Hard to tell with only the one line of HTML. You'd have to provide more of the HTML of the page. Try it again but get the value instead of text.

WebElement element = driver.findElement(By.cssSelector("input[style='text-align:center']"));
System.out.println(element.getAttribute("value"));

Does that work? You likely will have to provide some unique HTML that surrounds the INPUT that we can use to make the CSS selector more specific.

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.