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

Android中如何获取网页脚本生成的文本?

问题:获取动态生成的网页文本内容

我想要提取某网页上显示的文本,达到手动复制后粘贴到记事本(无格式)的效果,但网页内容是通过多个脚本动态生成的,试了多种方法都无法获取这些脚本生成的文本。

尝试的方法1:用Jsoup下载网页并识别脚本

我写了以下代码来下载网页并识别页面中的脚本:

private fun getWebpageUsingJsoup(url: String): String {
    val document = Jsoup.connect(url).get()
    document.select("script").forEach {
        Log.d(TAG, "Found script $it")
    }
    return document.body().text()
}

这段代码能识别到页面中的脚本,但不会执行它们。网页里的脚本内容如下:

<body>
<script src="runtime.js" type="module"></script>
<script src="polyfills.js" type="module"></script>
<script src="vendor.js" type="module"></script>
<script src="main.js" type="module"></script>
</body>

尝试的方法2:用ScriptEngine执行脚本

参考相关内容后,我添加了代码尝试执行这些脚本:

val engine = ScriptEngineManager().getEngineByName("rhino")
document.select("script[type=module]").forEach { // 过滤掉GoogleAnalytics脚本
    val script = Jsoup.parseBodyFragment(it.data())
    Log.d(TAG, "Attempting to execute script $it")
    val returnValue = engine.eval(script.html())
    Log.d(TAG, "Engine returns\n$returnValue")
}

但执行后得到的输出完全不符合预期,四个脚本的输出都是:

<html>
<head/>
<body/>
</html>

现在我完全没头绪,不知道该怎么获取网页上显示的文本,求可行的解决方法。

补充:使用的依赖

implementation 'org.jsoup:jsoup:1.15.4'
implementation 'io.apisense:rhino-android:1.0'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:23:14