merlin
merlin

Reputation: 2927

Xpath: Get text within tag containing other tags

I am trying to get a price within a span with xpath. Since it contains a span within, the only value I get is \n:

HTML:

<span class="price--default is--nowrap is--discount">
                <span class="price--label">Unser Preis:</span> 19,95&nbsp;€
        </span>

Try to get value with xpath:

>>> selector.xpath(".//span[contains(@class, 'price--default')]/text()").extract_first()
'\n'

Trying it with following-sibling:

>>> selector.xpath(".//span[contains(@class, 'price--default')]/following-sibling::text()").extract_first()
'\n'

How is it possible to get the price with the span tag?

Upvotes: 2

Views: 1484

Answers (2)

Jack Fleeting
Jack Fleeting

Reputation: 24930

Another thing to try:

.//span[span]/text()

Upvotes: 0

kjhughes
kjhughes

Reputation: 111726

You were on track with your following-sibling:: attempt, but change the XPath,

.//span[contains(@class, 'price--default')]/following-sibling::text()

to

.//span[contains(@class, 'price--label')]/following-sibling::text()

because it's the inner span after which you wish to select the following sibling text node.

Note: If you know there's a single class attribute value, use = rather than the string containment predicate:

.//span[@class='price--label']/following-sibling::text()

If there could be multiple class attribute values, then use the space-padded idiom described here: XPath to match @class value and element value?

Upvotes: 1

Related Questions