You need to enable JavaScript to run this app. Android开发:Jsoup爬取数据后如何正确使用爬取值做if判断
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:Jsoup爬取数据后如何正确使用爬取值做if判断

Jsoup爬取雅虎财经比特币价格实现阈值判断的问题

开发背景

  • 基于Android Studio开发,使用Jsoup爬取雅虎财经BTC-USD交易对的页面行情数据
  • 基础功能已打通:可正常发起网络请求获取页面元素,并将爬取到的比特币价格展示在页面的TextView控件中
  • 预期实现效果:将爬取到的实时比特币价格与70000的阈值做对比,根据价格高于/低于阈值的结果,展示对应的提示文本

异常表现

  • 编写if条件判断逻辑、引入数值解析流程做价格对比时,点击触发请求的按钮后应用无任何响应,即使if、else两个分支原本都配置了输出比特币价格的逻辑,TextView也无内容展示
  • 项目可正常构建APK,无编译阶段报错
  • 复现验证:同时删除if判断语句块、以及foo = Double.parseDouble(String.valueOf(quote));这行代码后,应用可正常拉取数据并在TextView中展示比特币价格

已尝试的无效解决方式

  • 尝试使用Integer.parseInt(quote.text())等方法将爬取到的价格转为数值类型,用于if条件判断,此时应用无任何内容展示
  • 即便调整if分支逻辑,让两个分支都返回比特币价格文本,依然无法触发正常的页面渲染

现有实现代码

public class MainActivity extends AppCompatActivity {

    TextView texx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        texx = (TextView) findViewById(R.id.textView);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new doit().execute();
            }
        });
    }

    public class doit extends AsyncTask<Void, Void, Void> {

        String word;
        double a = 70000;
        double foo;

        @Override
        protected Void doInBackground(Void... voids) {

            String url = "https://finance.yahoo.com/quote/BTC-USD?p=BTC-USD&.tsrc=fin-srch";

            try {
                Document doc = Jsoup.connect(url).get();
                Element quote = doc.select("span[data-reactid='32']").first();

                foo = Double.parseDouble(String.valueOf(quote));

                if (foo < a) {
                    word = quote.text();
                } else {
                    word = quote.text();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            texx.setText(word);
        }
    }
}

内容的提问来源于stack exchange,提问作者Sir-Samuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 20:27:03