1

For learning purpose i am trying to write a simple currency converter. I want to get the updated rate from Google.

public void Google() throws IOException {
    String url="https://www.google.com/finance/converter?a=1&from=USD&to=BDT";
    URL theUrl=new URL(url);
    URLConnection openUrl=theUrl.openConnection();
    BufferedReader input = new BufferedReader(new InputStreamReader(openUrl.getInputStream()));
    String result=null;
    while ((result=input.readLine()) != null){
        System.out.println(result);

    }
    input.close();

}

It gets me the html source:

<div id=currency_converter_result>1 USD = <span class=bld>77.9284 BDT</span>

So i only need the rate 77.9284 BDT and store it in a variable.

I am not getting any idea how to do it! Do i need somekind of regex?

Any help will be appreciated !

u4547878
  • 197
  • 4
  • 13

3 Answers3

0

You can use jSoup library it parses html data in java And from there you can get the value of the span with class bdt.

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
0

If you don't want to use a library, you can use the Pattern class but is not a good idea to parse HTML/XML with regex. See this post: Question about parsing HTML using Regex and Java

public void Google() throws IOException {
    URL url = new URL("https://www.google.com/finance/converter?a=1&from=USD&to=BDT");
    URLConnection openUrl = url.openConnection();

    BufferedReader input = new BufferedReader(new InputStreamReader(openUrl.getInputStream()));

    String result = null;
    Pattern pattern = Pattern.compile("([0-9]*.?[0-9]* BDT)");

    while ((result = input.readLine()) != null) {
        Matcher matcher = pattern.matcher(result);
        if (matcher.find()) {
            System.out.println(matcher.group());
            break;
        }
    }
    input.close();
}
Community
  • 1
  • 1
Jesus Zavarce
  • 1,729
  • 1
  • 17
  • 27
-1

To extract the DOM elements effectively, you can use jsoup library to parse the html content.

Please use the below code snippet (import org.jsoup package at class level) for your requirement:

    public void google() throws IOException {
        Document doc = Jsoup.connect("https://www.google.com/finance/converter?a=1&from=USD&to=BDT").get();
        Element element = doc.getElementById("currency_converter_result");
        String text = element.text();
        System.out.println(text);
    }
Vasu
  • 21,832
  • 11
  • 51
  • 67