2016-10-30 7 views
2

学習目的のために、私は単純な通貨コンバータを作成しようとしています。私はGoogleから更新されたレートを取得したい。URLの内容からjava変数の値を取得する

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

} 

それは私のHTMLソースを取得:だから私は唯一率77.9284 BDTを必要とし、変数に格納

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

を。

どうすればいいのか分かりません。正規表現の何かが必要ですか?

ご協力いただければ幸いです!

答えて

0

DOM要素を効果的に抽出するには、jsoupライブラリを使用してHTMLコンテンツを解析できます。

あなたの条件のために(クラスレベルでimport org.jsoup package)以下のコードを使用してください:あなたは、ライブラリを使用したくない場合は、あなたがPatternクラスを使用しますが、良いアイデアではありませんすることができ

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

このソリューションは私のニーズに非常に近いです。 kodr

+0

要素r = element.getElementsByClass(" bld "); worked – kodr

+0

部分文字列を使用できます:String dollarValue = text.substring(text.indexOf ( "=")+ 2)。 – developer

0

あなたはjavaのhtmlデータを解析するjSoupライブラリを使うことができます。そこから、クラスbdtでスパンの値を取得できます。

0

regexでHTML/XMLを解析するこのポストを参照してください: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(); 
} 
関連する問題