You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Jsoup爬取Google Play Store版本名时遇空指针异常求助

解决Jsoup爬取Google Play版本号时的空指针异常

你遇到的空指针问题核心原因很明确:Google Play的页面结构已经更新——你原来依赖的div[itemprop=softwareVersion]选择器现在找不到对应元素了,导致.first()返回null,调用ownText()时触发了空指针异常。

我给你整理了修复方案和优化建议:

1. 替换为当前有效的CSS选择器

现在Google Play应用详情页的版本号DOM结构已经变更,不再使用itemprop=softwareVersion属性。目前可以通过匹配"Current Version"对应的内容块来获取版本号,修改后的doInBackground代码如下:

@Override
protected JSONObject doInBackground(String... params) {
    try {
        Document doc = Jsoup.connect("https://play.google.com/store/apps/details?id="+context.getPackageName()+"&hl=en")
                .timeout(30000)
                .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")
                .referrer("http://www.google.com")
                .get();
        
        // 匹配包含版本信息的元素组
        Elements versionElements = doc.select(".hAyfc .htlgb");
        if (versionElements.size() >= 2) {
            // 第一个元素是"Current Version"文本,第二个就是版本号
            latestVersion = versionElements.get(1).ownText();
        } else {
            // 兜底处理:找不到元素时设为null
            latestVersion = null;
        }

    } catch (IOException e) {
        e.printStackTrace();
        latestVersion = null;
    }
    return new JSONObject();
}

2. 强化空值安全判断

除了选择器的调整,还要在后续逻辑里处理latestVersion为null的情况,避免后续代码出现异常,修改onPostExecute:

@Override
protected void onPostExecute(JSONObject jsonObject) {
    if(latestVersion != null && !latestVersion.isEmpty()){
        if(!currentVersion.equalsIgnoreCase(latestVersion)){
            if(!(context instanceof SplashActivity) && !((Activity)context).isFinishing()){
                showForceUpdateDialog();
            }
        }
    } else {
        // 可选:提示用户无法检查更新
        // Toast.makeText(context, "无法获取最新版本信息", Toast.LENGTH_SHORT).show();
    }
    super.onPostExecute(jsonObject);
}

额外优化建议

  • 避免依赖页面结构爬取:Google Play的页面随时可能改版,这种爬虫方式稳定性差。更可靠的方案是使用Google Play Developer API获取应用最新版本号,不过需要配置开发者账号和API密钥。
  • 替换AsyncTask:AsyncTask在Android 11及以上已被废弃,建议改用Kotlin协程或Java的ExecutorService执行网络异步操作,符合现代Android开发规范。
  • 检查网络权限:确保你的AndroidManifest.xml中已声明网络权限:
    <uses-permission android:name="android.permission.INTERNET" />
    

内容的提问来源于stack exchange,提问作者Anil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:13:32