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 !

0

3 Answers 3

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.

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

Comments

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();
}

Comments

-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);
    }

3 Comments

This solutions very close to my needs. Is it possible to get only the BDT result which is in <span class="bld>?
Elements r = element.getElementsByClass("bld"); worked
You can use substring: String dollarValue = text.substring(text.indexOf("=")+2);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.