user2430491
user2430491

Reputation: 1

Selenium getText() not working

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!

Upvotes: 0

Views: 2227

Answers (2)

Dirk
Dirk

Reputation: 3093

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.

Upvotes: 0

Jim Barrows
Jim Barrows

Reputation: 3634

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

Upvotes: 1

Related Questions