Selenium getText() not working - java

So for my project, I'm using Selenium to check that significant fields are in my DOM. The XML I am analyzing is below:
<results>
<result index="1">
<track>
<creator>God</creator>
</track>
</result>
<results>
For the first thing, I get a list of all result tags as webElements by running:
List<WebElement> result_list = driver.findElements(By.tagName("result"));
I then do a for loop in order to check that the creator tag is there by running
try {
for (int i = 0; i < result_list.size(); i++) {
WebElement track = result_list.get(i).findElement(By.tagName("track"));
System.out.println(track.findElement(By.tagName("creator")).getText());
System.out.println(track.getTagName());
System.out.println(track.getAttribute("creator"));
}
result = true;
}
catch (Exception e) {
result = false;
}
I have inserted print statements in order to see what each tag is saying. I'm new to selenium so I'm just trying to make sure that I'm iterating correctly for the web elements, meaning each call to getText and getAttribute should be different for each iteration of the loop. Only problem is that I get an empty string printed out for each getText() call and null for each getAttribute() call. Why is this happening? Output below.
<empty string> (nothing is printed, just illustrating the empty string)
track
null
Any help would be greatly appreciated!

Selenium doesn't handle XML. It's HTML only. Please read the documentation, it's quite clear.
There might be a plugin

WebElement.getAttribute(String) is not returning what you expect because there's a slight misunderstanding of what an attribute is. The attribute of an element is defined within the tag of the element ('id', 'name', 'style', etc.).
What you're trying to do is look for a child element of <track> when instead what you're doing is trying to look for <track creator="a_creator"> which would return what you're expecting.
I've never been able to get WebElement.findElement() to work on another WebElement without dropping down to xpath. So something like:
WebElement parent = driver.findElement(By.id("parent"));
WebElement child = parent.findElement(By.tagName("child"));
Never seems to work. However, in this case something like:
WebElement parent = driver.findElement(By.id("parent"));
WebElement child = parnet.findElement(By.xpath(".//creator"));
Should work. If you're new to xpath, you may want to consider a quick run through some basic tutorials.

Related

How to choose an element from divs having the same classnames (Selenium)

I am new to Selenium which is probably why I am stuck.
Here is the screenshot showing inspect where two divs are almost identical but they both have another div inside containing different text values: Image.
Could I somehow choose the div I want by checking if getText() is equal to ...?
I found the following way but as far as I know, I would never know the order of the stream:
new ArrayList<>(chromeDriver.findElements(By.xpath("//div[#class='sign-up-row']"))).get(1).click();
Thank you guys.
Using Xpath like below:
example for //div[#class='sign-up-row'] this node
use text():
//div[#class='sign-up-row' and .//span[text()='Remember me.')]]
Or use with contains:
//span[contains(text(), 'Remember')]/ancestor::div[#class='sign-up-row']
Use the dot . can find inner element:
//div[#class='sign-up-row' and contains(., 'Remember')]
You can create an xpath using the text present in the tag within the div tag. This would return the specific element you are interested in.
Example for the xpath:
//div/div[text()='textforcomparison']
You can follow below approach.
List<WebElement> lst = driver.findElements(By.xpath("//div[#class='sign-up-row']"));
for (int i = 0; i < lst.size(); i++) {
if(lst.get(i).getText().equals("Text to Be Compared")) {
lst.get(i).click();
//If you want to break the foe loop after the match
break;
}
}

How to find element having dynamic ID / Name changing on every page load using Selenium WebDriver

I found a few answers about this but they did not answer my question an so I am writing a new question.
I have HTML code having below kind of checkbox elements (in browser's inspect element)
<input role="checkbox" type="checkbox" id="jqg_TransactionFormModel501EditCollection2_147354_grid_-1274" class="cbox" name="jqg_TransactionFormModel501EditCollection2_147354_grid_-1274" value="true">
In my test case I want to click on checkbox using its ID using Selenium Webdriver.
here Id= "jqg_TransactionFormModel501EditCollection2_147354grid-1274" is dynamic.
in above id, Bold & Italic marked letters (dynamic) will change with different check boxes in same page as well as page refresh.
Bold marked letters (dynamic) will change on page refresh only (remain same through all the check boxes in same page.)
How shoud I format/write XPATH so that I can click on desired check boxes using below statement.
WebElement checkbox = webDriver.findElement(By.id("idOfTheElement"));
if (!checkbox.isSelected()) {
checkbox.click();
}
Thanks for your help in advance.. !
Here are a few examples of xpaths which you can use to find your checkbox
//input[contains(#id,'jqg_TransactionFormModel')]
OR, if you want more checks, try something like
//*[starts-with(#id,'jqg_TransactionFormModel') and contains(#id,'EditCollection2_')]
Additionally, you can try regex as well using matches
//*[matches(#id,'<regex matching your id>')]
You can use partial ID using cssSelector or xpath
webDriver.findElement(By.cssSelector("[id*='TransactionFormModel']"));
webDriver.findElement(By.xpath("//input[contains(#id, 'TransactionFormModel')]"));
You can replace TransactionFormModel with any other fixed part of the ID.
As a side note, no need to locate the element twice. You can do
WebElement checkbox = webDriver.findElement(By.id("idOfTheElement"));
if (!checkbox.isSelected()) {
checkbox.click();
}
You can write xpath like this :
//input[starts-with(#id,'jqg_TransactionFormModel')]
//input[contains(#id,'jqg_TransactionFormModel')]
I recommend not using ID's or xpath and adding a data attribute to your elements. This way, you can avoid the annoyance of xpath and have a strong selector that you feel confident will always be selectable.
For example, you could call the attribute: data-selector. You can assign a value of "transactionFormModelCheckbox". Then, when creating a new element, you create by css selector with the value referenced above.
No matter what type of formatting, you'll always be able to select that checkbox - as long as the element exists in the DOM. If you need to investigate other attributes, you can use the selector to do things like hasClass() or anything else you need.
Hope that helps !

Selenium says invalid xpath locator

I am trying to get value of HREF attribute but always it says incorrect Xpath.
Html Code :
I am trying code :
WebElement Link = driver.findElement(By.xpath("//table[contains(#class,'display')]/thead/tbody/tr/td/a"));
System.out.println(Link.getAttribute("href"));
I tried many xpath but none of them worked.
This should work:
WebElement Link = driver.findElement(By.xpath("//table[contains(#class,'display')]/tbody/tr/td/a"));
Explanation: tbody is not nested in thead.
Note that a path expression like this can return a set of several nodes, in document order. The findElement method only returns the first result node. So: if the a element you are looking for is no longer the first one in this table, the path expression breaks.
If the the href is unique, something like this would be less error-prone:
WebElement Link = driver.findElement(By.xpath("//table[contains(#class,'display')]//a[#href='/admin/client/product_overrides/edit/242625']"));

how to get a text string from

I am creating an automatic test for some webs and I'm using WebDriver, TestNG and code that is written in Java. On the page is shown register of categories, in parentheses is number of auctions and i need to get this number as variable, but i don't know, how.
I use the following code:
WebElement number1_1_vse = (driver.findElement(By.linkText("Vše")));
String text_vse1_1 = number1_1_vse.getText();
but output is only: "Vše" without (number of auctions)
link to the website
screenshot -> image with the number
can anyone advise me please?
With linktext you are finding the nested a which text is Vše only. You need to find the li containing the text Vše (949)
Use the following css selector to identify the element
By bycss =By.cssSelector(".list.list-categories>li:first-child");
WebElement number1_1_vse = driver.findElement(bycss );
String text_vse1_1 = number1_1_vse.getText();
WebElement parent = number1_1_vse.findElement(By.xpath(".."));
// which will give you access to <li>
List<WebElement> childs = parent.findElements(By.xpath(".//*"));
// childs.get(1) has the result.
Please try to get the xpath value and then try to search it with below mentioned syntax :
findelementbyxpath("//*[#id="post-form"]/h2")
To get xpath value of and element : right click --> inspect element --> right click copy xpath

NoSuchElementException when using By.Xpath

Edit :
The element was inside an iframe, this is how it finally worked:
WebDriverWait wait = new WebDriverWait(_driver, 60);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By
.xpath("//*[#class='IFrameID']")));
WebElement element_t = _driver.findElement(
By.xpath("//*[#myattribute='mytest']"));
Edit :
My problem seems to be the structure of the page. i tried different things, and i only was able to get the body by id, ever other element i tried to get by id or any other attribute couldnt be found...
I am trying to get an element by using the By.xpath method, the xpath itself works just fine when used in firebug/firepath, but when used in the java application i am getting an Exception:
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[#myattribute='mytest']"}
The attribute i am trying to access is not a standard html one, but generated from a framework so the field looks like this :
<input id="F_19" class="FIELDInputEdit" type="text" style=" width:100%;" maxlength="40" myattribute="mytest" name="CC">
The javacode itself looks like this :
WebElement element_t = _driver.findElement(
By.xpath(".//*[#myattribute='mytest']"));
Since the only known attribute is this one, i have no ohter way to access the input field.
I am using Firefox 17.0.11
good practice (imho) before using xpath in webdriver test it using selenium ide (http://docs.seleniumhq.org/download/)
Error might be because of «.» before «//». Try to remove it.
Read this: http://www.w3schools.com/xpath/xpath_syntax.asp
.//*[#myattribute='mytest']
«.» = Selects the current node
«//» = Selects nodes in the document from the current node that match the selection no matter where they are
«*» = Matches any element node
«[#myattribute='mytest']» ( = [#myattribute = \"mytest\"]) = Node, that contains attribute "myattribute", which value is "mytest"
Now, _driver.findElement(By.xpath("//*[#myattribute='mytest']")) = search whole page for first node with attribute «myattribute» with value «mytest»
_driver.findElement(By.xpath("//input[#myattribute='mytest']"))
= search whole page for first input with «myattribute» = «mytest»
_driver.findElement(By.xpath("//input[#myattribute='mytest']")).then(By.path("./*[#comeAtr]")) = in input with «myattribute» = «mytest» find any node with atribute = «
Have you tried to use CSS selectors instead?
By.cssSelector("input[myattribute=\"mytest\"]")
The element was inside an iframe, this is how it finally worked:
WebDriverWait wait = new WebDriverWait(_driver, 60);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By
.xpath("//*[#class='IFrameID']")));
WebElement element_t = _driver.findElement(
By.xpath("//*[#myattribute='mytest']"));

Categories

Resources