Selenium: find element "next to" other element - java

I'm adding web tests to my project using Selenium. I already have a bunch of tests that check for a specific element using:
final WebElement dateElement = web.findElement(By.id(elementId));
And this works fine.
Now I have another requirement. This is in my generated page:
<input type="text" id="dateElement" name="dateElement" value="bunch of monkeys" tabindex="101" placeholder="yyyy-mm-dd">
<span class="error">dateElement is an invalid date</span>
How can I get hold of the error message?
I'd like something that allows me to request the span element with class "error" that is just after dateElement.
(This error message was ganerated by Spring MVC, so it's not easy to change it directly. Possible I guess, but I'd prefer not).
Any alternative idea is welcome.

OK, I already found a solution using Xpath and following-sibling, it wasn't too complicated.
final WebElement errorElement = web.findElement(By.xpath("//*[#id='" + elementId + "']/following-sibling::span[#class='error']"));
This gives me what I wanted, and throws a NoSuchElementException when it's not here, which is exactly what I want.

elementSelector = "input + span[class='error']";
final WebElement dateElement = web.findElement(By.cssSelector(elementSelector));

Related

How to verify ::after pseudo-element if exist in selenium

I am working with a pre-defined field so you can only enter specific values and if you enter any other value (which is not mapped in database) then it throws error.
Now, I want to check for which values (from excel sheet), this field throws error but I am struggling to achieve this because the only things which changes in the DOM for invalid value is ::before. If it is invalid ::before will appear.
Example:
<label for="Broom" data-error="Please." class="active">::before</label>
When I came across this problem, I could not see any way of doing this through the WebDriver locator strategy like XPATH, CSS etc. We can only use this via Javascript. Something like this:
public String errorCheck() {
String script = "return window.getComputedStyle(document.querySelector('label[for=\\'Broom\\']'),':before').getPropertyValue('content')";
JavascriptExecutor js = (JavascriptExecutor)driver;
String content = (String) js.executeScript(script);
return content;
}
So, you can verify if it returns null for valid values. If you do more research around this, you will find you can do more validations as well i.e colour etc.
This is more from reference point of view.

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.
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.
You can use the By-selector only for elements inside of the tag.
To get the text of an element
you can use
driver.findElement(By.xpath("//span[#class='numfound']")).getText();
or (if you like more):
driver.findElement(By.className("numfound")).getText();
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.
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

How can I get the inner text of an element in Selenium?

I'm working with a DOM node:
<input
type="form-control"
type="text"
data-bind="textInput: EnterpriseId"
disabled
autocomplete="off">
How can I get its value? I'm struggling since element.getText() does not work and returns a blank.
Try this:
WebElement element = driver.findElement(By.id("id value"));
String val = element.getAttribute("innerText")
I presume the element in question is an <input> element, so you may be able to use the element.getAttribute(String attribute) method like so:
String value = element.getAttribute("value");
This input tag is disabled, hence element.getText() returns a blank value.
Use element.getAttribute("textContent") instead.
You may be looking for the placeholder of an input text, because you might try:
element.getAttribute("placeholder");
You can go to your browser → open developer tools → inspect element you want to take attribute from → click Properties → check if that value is in InnerText.
Then do as it is mentioned in previous comments:
element_locator.get_attribute('InnerText')
I had the exact same issue! This post solved it for me:
How can I get the current contents of an element in webdriver
I used:
element = driver.find_elements_by_xpath(
'//button[#class="size-grid-dropdown size-grid-button"]')
element.text
As other's suggested, HTML's input nodes don't have a text attribute because they can store data in multiple formats in a value attribute.
This can be easily seen in the HTML input API specification where this form control can be of type radio, date, file upload and many more.
So, in your specific case, I'd suggest you check the webdriver's API for a method that's able to retrieve the value attribute.
As a bonus to evaluate innerText of an element within Selenium:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("yourEl")));
wait.until(ExpectedConditions.attributeToBe(By.id("yourEl"), "innerText", yourValue));
Documentation: attributeToBe
It works definitely, as I've tested it several times:
<input type="form-control" type="text" data-bind="textInput: EnterpriseId" disabled autocomplete="off">
In your example, you don’t have any innerText. So you can only get attributes as mentioned before with the existing attributes. In your case:
type, data-bind, EnterpriseId and autocomplete. No value will be as this attribute isn’t created.
If you want to get only existing, this should be fine:
String example = driver.findElement(ByLocator(("")).getAttribute("any attribute of your input");
System.out.println(example);

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

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.
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...:)
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']")

Obtain Selenium WebElement from cssSelector over HTML Input

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
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.
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.

Categories