user3645276
user3645276

Reputation: 51

getting the class name of an HTML tag using XPATH

Suppose we have this span tag <span class="my-FAV_numberis49"></span> enclosed in a complicated document like this:

<div id="box_content">
    <div class="heading">
        Description
    </div>
    Really cool description about something really cool.
    <br>

    <div class="more_detail">

    </div>
    <div class="more_detail">
        <span class="date">Today's Date is</span>June 06 2014
    </div>
    <span class="my-FAV_numberis49"></span>
</div>

How can I save the name of the span class only(i.e. "my-FAV_numberis49") Let us assume that the format of the document will be unchanged, but the span class name can change to something like "my-FAV_numberis7". Is there a way to do this?

I hope my question is clear. Thank you for your assistance.

Upvotes: 1

Views: 13167

Answers (3)

herongwei
herongwei

Reputation: 1

the first answers is userful

//div[@id='box_content']/span[contains(@class, 'my-FAV_numberis')]
exact the class name try //span[starts-with(@class, 'my-FAV_numberis')]/@class

Upvotes: 0

Joel M. Lamsen
Joel M. Lamsen

Reputation: 7173

try

//span[starts-with(@class, 'my-FAV_numberis')]/@class

it says look for a span tag with an attribute class that starts-with my-FAV_numberis and output its class attribute contents.

Upvotes: 2

helderdarocha
helderdarocha

Reputation: 23637

This XPath expression will select all the span elements that are children of the div with an ID of box_content that have a class attribute which contains the string my-FAV_numberis.

//div[@id='box_content']/span[contains(@class, 'my-FAV_numberis')]

It will match my-FAV_numberis49, my-FAV_numberis7 and any string that contains my-FAV_numberis, including other-class my-FAV_numberis99 and this-56-my-FAV_numberisnothere.

If there is more than one span that matches in this context, a node-set will be selected. You can avoid that adding more restrictions or a positional predicate.

If the span is the last span child element in that context you can use:

//div[@id='box_content']/span[last()]

This is based on the example you provided. If the span element is not always a child of div and may sometimes be inside another element, then you can use the descendant axis:

//div[@id='box_content']//span[last()]

which will select the last span that occurs inside the div, in any level.

EDIT: to extract the class name from the span element you can use:

//div[@id='box_content']//span[last()]/@class

Upvotes: 5

Related Questions