0

I need to select the particulr text from webpage using XPATH. My Text looks like below

The "Add Account Offer" request has been submitted successfully with the order number css_334560. 

In the above line i need to get only "css_334560" using XPATH. Can someone help me here?

HTML :-

<div id="secondColumn" class="floatBreaker"> <div id="mainContents"> <h1>Add Account Offers </h1> <div class="infoBox"> <div class="topLine"> <div class="txtLineRight"> <div class="txtLineLeft"> <div class="txt"> <span>The "Add Account Offer" request has been submitted successfully with the order number css_334560.</span> </div> </div> 
1
  • 1
    You won't get only css_334560 using Selenium rather you'll get entire text in span tag. Commented Apr 14, 2014 at 14:08

2 Answers 2

1

You can use the following code if you use Java:

String a = driver.findElement(By.xpath("//div[@class='txt']/span")).getText(); a = a.substring(a.lastIndexOf(' ') + 1).replace(".", ""); 

First row gets text from span. Second row takes css_334560. and removes dot.

Html code is not full, so I can't guaranty that xpath is correct.

Sign up to request clarification or add additional context in comments.

Comments

0

There are a few possibilities which depends on the situation.

1- Getting a text node that includes a certain text: I used "Add Account Offer" but you can use "css_" or any other text that would be unique to that text node.

If there are a few matching text nodes: (get them and loop through them, checking them one by one)

var snapElements = document.evaluate( './/text()[contains(.,"Add Account Offer")]', document.body, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); 

If there is only ONE matching text node

var txt = document.evaluate( './/text()[contains(.,"Add Account Offer")]', document.body, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); 

2- On the other hand, if <div class="txt"> is unique (there is only one on the page), if it faster to get it by:

var txt = document.querySelector('.txt'); if (txt) { txt = txt.textContent; } 

Also possible ...

var txt = document.getElementsByClassName('txt'); if (txt[0]) { txt = txt[0].textContent; } 

After getting the whole text, now you can use (for example) a RegEx to get the desired section ... for example:

var css = txt.match(/css_\d+/); 

Good luck :)

2 Comments

The only problem with this answer is the context - Selenium. Selenium expects physical DOM elements to be returned from a given XPath selector, your first two XPath's won't return a DOM element.
Thank you Arran ... I am not familiar with Selenium so my answer was based on standard HTML/DOM :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.