How to use Selenium using Xpath to determine the classes of an element?

Z374_13y73z picture Z374_13y73z · Jun 25, 2013 · Viewed 8.9k times · Source

I am trying to use xpath within selenium to select a div element that is within a td. What I am really trying to do is determine the class of the div and if it is either classed LOGO1, LOGO2, LOGO3 and so on. Originally I was going to just snag the image:url to determine with logo.jpg was used but whoever made the target website used one image for each logo type and used css to determine which portion of the image will be displayed. So Imagine 4 images on one sprite image. This is the reason why I have to determine the class of the div instead of digging through the css paths.

In selenium I am using storeElementPresent | /html/body/form/center/table/tbody/tr/td[2]/div[3]/div[2]/fieldset/table/tbody/tr[2]/td/div/table/tbody/tr[${i}]/td[8]/div//class | cardLogo .

The div has multiple classes so I am thinking that this is the issue, but any help is appreciated. Below is the target source. This is source from within the table in the tbody. Selenium has no problems identifying all the way up to td[8] but then fails to gather the div. Please help!

<td class="togglehidefields" style="width:80px;">
<div class="cardlogo LOGO1" style="background-image:url(https://www.somesite.com/merchants/images/image.jpg)"></div>
<span id="ContentPlaceHolder1_grdCCChargebackDetail_lblCardNumber_0">7777</span>
</td>

I was fiddling with selenium.getAttribute() but it kept erroring out, any ideas there?

Answer

Jens Erat picture Jens Erat · Jun 25, 2013

This <div/> element has one class attribute with one value, but this one is tokenized when parsed as HTML.

As selenium only supports XPath 1.0, you will need to check for classes like this:

//div[contains(@class, "LOGO1") or contains(@class, "LOGO2")]

Extend that pattern as needed and embed it in your expression.

With XPath 2.0 and better, you could tokenize and use the = operator which works on a set-based semantics:

//div[tokenize(@class, ' ') = ("LOGO1", "LOGO2")]