24
<td width="10"></td>
<td width="65"><img src="/images/sparks/NIFTY.png" /></td> 
<td width="65">5,390.85</td>
<td width="65">5,428.15</td>
<td width="65">5,376.15</td>
<td width="65">5,413.85</td>

This is the HTML source from which i have to extract the values 5390.85,5428.15 , 5376.15 , 5413.85. I wanted to do this using jsoup. But i am relatively new to jsoup( today i started using it). So how should i do this?

URL url = new URL("http://www.nseindia.com/content/equities/niftysparks.htm");
Document doc = Jsoup.parse(url,3*1000);
String text = doc.body().text();

I have already extracted the content of the website using jsoup. but how to extract the values i require? Thanks in advance

Alkis Kalogeris
  • 17,044
  • 15
  • 59
  • 113
CyprUS
  • 4,159
  • 9
  • 48
  • 93
  • 2
    Came across another example http://technology.amis.nl/blog/13121/screenscraping-from-java-using-jsoup-effective-data-gathering-from-websites – 2sb Jan 09 '12 at 18:31

2 Answers2

33

Try something like this:-

URL url = new URL("http://www.nseindia.com/content/equities/niftysparks.htm");
Document doc = Jsoup.parse(url, 3000);

Element table = doc.select("table[class=niftyd]").first();

Iterator<Element> ite = table.select("td[width=65]").iterator();

ite.next(); // first one is image, skip it

System.out.println("Value 1: " + ite.next().text());
System.out.println("Value 2: " + ite.next().text());
System.out.println("Value 3: " + ite.next().text());
System.out.println("Value 4: " + ite.next().text());

Here's the printout:-

Value 1: 5,390.85
Value 2: 5,428.15
Value 3: 5,376.15
Value 4: 5,413.85
limc
  • 39,366
  • 20
  • 100
  • 145
6

Here's an example using Groovy lang:

def url = "http://www.espn.co.uk/scrum/rugby/match/scores/recent.html"
def doc = Jsoup.connec(url).get()

//Strip the table from the page
def table = doc.select("table").first()
// Strip the rows from the table
def tbRows = table.select("tr")

// For each column in a row, print its contents if not empty
tbRows.each { row ->
    def tbCol = row.select("td")
    tbCol.each { column ->
        if(!column.text().empty) {
            println column.text()
        }
    }
}

You could save this to an array for further processing. Just another perspective.

Sion
  • 395
  • 4
  • 15