Get text found between span - selenium - java

Inspect element from Google Chrome:
<div class="form-style-abc">
<fieldset>
<legend><span class="number">*</span>Search Zone</legend>
Need to retrieve the "Search Zone", however im unable to perform the search and getText()
I had performed the following on Eclipse but getting error:
Code:
String HeaderTxt = driver.findElement(By.xpath("//span[#class = 'number']")).getText();
System.out.println(HeaderTxt);
Error Message:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//span[#class = 'number']"}

As per the HTML you have provided to extract the text Search Zone you can use the following line of code :
String HeaderTxt = driver.findElement(By.xpath("//div[#class='form-style-abc']/fieldset/legend[(self::legend) and not (#class='number')]")).getText();
System.out.println(HeaderTxt);
Update 1
As per your comment update as you are still seeing NoSuchElementException possibly you need to wait for the element inducing WebDriverWait as follows :
WebElement HeaderTxtElem = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='form-style-abc']/fieldset/legend[(self::legend) and not (#class='number')]")));
System.out.println(HeaderTxtElem.getText());
Update 2
As you mentioned the element is within an <iframe> tag you need to switch to the exact frame and then look out for the WebElement. Here you can find a detailed discussion on How to switch to frame in Selenium Webdriver Java
Update 3
Xpath Explanation
Through the xpath as "//div[#class='form-style-abc']/fieldset/legend" we have reached till the <legend> node. Now you want to get the text Search Zone only. So being within the <legend> tag you have to trim the child <span> tag which have a class as number. So we added a clause within our xpath not to consider (#class='number') while retrieving the text as in :
String HeaderTxt = driver.findElement(By.xpath("//div[#class='form-style-abc']/fieldset/legend[(self::legend) and not (#class='number')]")).getText();

Related

Unable to locate elements on a website , i tried all the locators but I get the error "No such element" . I am a self taught beginner to Automation

Element HTML:
Inbox
What I tried:
driver.findElement(By.cssSelector("a[text='Log out']"));
then
driver.findElement(By.xpath("//a[.='Log out']"));
Element snapshot:
HTML
driver.findElement(By.linkText("Log out"));
Something like that should work, you should provide the page html for a better response.
My response is based on the fact that in your first try you are saying text='Log out'.
findElement in selenium works with locatorStrategies (By.cssSelector/By.linkText...) the one that i used (linkText) search in all the anchor tags that are found in the pages () and analyze the text inside the tag, if the text is matched the driver will find the element.
Let me know if it works, otherwise provide me the web page html snippet.
I've seen the actual screen, you must change Log out with Inbox
driver.findElement(By.linkText("Inbox"));
Given the HTML:
Inbox
You need to take care of a couple of things here as follows:
Within cssSelector doesn't supports the :contains("text") method
Within xpath for exact text matches you need to use text()
Solution
To identify the element you can use either of the following locator strategies:
Using linkText:
WebElement element = driver.findElement(By.linkText("Log out"));
Using cssSelector:
WebElement element = driver.findElement(By.cssSelector("a[href$='INBOX'][title='View the Inbox']"));
Using xpath:
WebElement element = driver.findElement(By.xpath("//a[text()='Inbox' and #title='View the Inbox']"));

GetText() clarification - xpath not returning the value

Html:
<strong class="text-xl ng-binding" ng-bind="summary.PublishedIssuedRecent">5</strong>
my xpath:
#FindBy(how = How.XPATH, using = "//strong[#ng-bind='summary.PublishedIssuedRecent']")
public WebElement countRecentlyPublishedApplication;
String pubCount = countRecentlyPublishedApplication.getText();
my Expectation
i want to extract the value of 5
but i'm getting empty value in the pubCount String, Please suggest if any mistake in my xpath
From attribute ng-bind I'm guessing you're trying to scrap angularJS application and you're using selenium web driver.
Problem with angular is, it is rendered by javascript after the page loads. So on beginning element you want to scrap might not be there. Solution might be to wait a second until angulars finishes rendering and then try to find element.
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
WebElement pubCount = driver.findElement(By.xpath( "//strong[#ng-bind='summary.PublishedIssuedRecent']")).getText();
The XPath expression in itself is correct, it selects your node as expected. A simple test with xmllint gives:
> xmllint --xpath "//strong[#ng-bind='summary.PublishedIssuedRecent']" ~/test.html
<strong class="text-xl ng-binding" ng-bind="summary.PublishedIssuedRecent">5</strong>
So the error is outside your XPath expression.
By the way, if you just need the text of the node, you can use
> xmllint --xpath "//strong[#ng-bind='summary.PublishedIssuedRecent']/text()" ~/test.html
5

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.

Get page element by title attribute - Selenium and Java

I'm trying to get the image which has the word "Collector" in its title and click on it.
This is the html code for the image and its link:
<a href="javascript:*command*" title="Level III: KPI Collector RYG of D D/Testing - SYS">
<img src="*unusable link because it's only valid for the specific page*" title="Level III: KPI Collector RYG of D D/Testing - SYS">
The <a> and <img> tags are nested in a table cell and some divs. I didn't write the html code so don't yell at me if it's ugly :p
Here is the java code where I try to do it:
WebElement trafficLight = driver.findElement(By.xpath("//img[contains(#title,'Collector')]"));
trafficLight.click();
The error I get is:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//img[contains(#title,'Collector')]"}
I'm pretty sure the xpath is ok so I don't think that's the issue.
As the img WebElement is within a frame, you will need to switch focus to that frame before you perform any action on that WebElement. You can do that using WebDriver's switchTo() method like so:
driver.switchTo().frame(frameLocator);
The frame locator can be either its (zero-based) index, name or id attribute, or a previously located WebElement.
Once you have switched focus to the required frame, you should then be able to interact with the WebElement using the same code in your initial post.
Please try this. It will resolve your problem.
WebElement frameSwitch = driver.findElement(By.xpath("Give iframe Xpath location"));
driver.switchTo().frame(frameSwitch); //Switch control to iframe.
//Perform your steps (I.e Click on Image)
driver.findElement(By.xpath("//img[contains(#title,'Collector')]")).click();
driver.switchTo().defaultContent(); //Come out of iframe.

Selenium Webdriver - Find dynamic id from li/a

I am trying to select a value(Bellevue) from a li(it looks like a dropdown but it isn't).The problem is that its id changes everytime the page loads.
Here is a screenshot:
This time the id is: ui-id-23,but the number,23,will be changed next time so this will not work.If I expand the <a id="ui-id-23..." I get the name 'Bellevue' but every character surrounded by < strong > < /strong > mark-up.
I can't find it after it's classname because both values from li have the same class,ui-menu-item.
I tried after xpath:"//a[contains(text(),'Bellevue')]" but I get the error:Unable to locate element...
Do you know any solution for this?I am using Selenium Webdriver in Java and TestNG.
Thanks!
Update
So I managed to find that element by using:
WebElement value = driver.findElements(By.cssSelector("a[id^='ui-id-']")).get(3);
value.click(); .
but in my application i am using page objects and i look after elements using #FindBy(how.HOW.....).Do you know how I can use .get(3) with #FindBy?
You want to use a CSS selector on the ID:
a[id^='ui-id-']
This says "Find all of the a elements that have an ID that start with ui-id-"
If you want to find the second item, then do:
driver.findElements(By.cssSelector("a[id^='ui-id-']"))[1]
The [1] will select the second item on the page.
It looks like jQuery uniquId() method is used to populated the id, so it will always start with ui-id-. You can use jQuery selector to select element whose id starts with ui-id-
WebElement webElement = (WebElement) ((JavascriptExecutor) webDriver).executeScript("return $( 'input[id^="ui-id-"]').get(0);");
I would try to use xpath avoiding using of id. For example, //a[#class=''ui-corner-all ui-state-focus ][2]
First get the tag name in which your id attribute has been defined.
WebElement ele = driver.findElement(By.tagName(tagName));
String strId = ele.getAttribute("id").startsWith("ui-id-");
driver.findElement(By.id(strId)).click();

Categories