0

我正在尝试从 url 获取 html 并操作 html,然后使用 GeckoView 呈现它

我打算使用 Jsoup 从 url 获取 html 字符串,但这表示使用 Jsoup 获取完整的 html 存在问题

所以我找到了另一种使用 GeckoView 获取 html 的方法(这个api 参考

所以我成功地从一个 url 获取了一个 html 字符串并只用 GeckoView 渲染它

这是代码

private fun setupGeckoView() { // I call this in the onCreate method
    geckoView = findViewById(R.id.geckoview)
    val runtime = GeckoRuntime.create(this)
    geckoSession.open(runtime)
    geckoView.setSession(geckoSession)
    val executor = GeckoWebExecutor(runtime)     
    val result = executor.fetch(    // from here i start getting the sourcecode inputStream
            WebRequest.Builder("https://google.com")
                    .header("Accept","Application/json")
                    .build())
    result.then { response ->
        htmlContentInStringFormat = response?.body?.bufferedReader().use { it?.readText() } 
        // ㄴ and i get the html string from the inputStream
        geckoSession.loadData(htmlContentInStringFormat!!.toByteArray(Charsets.UTF_8),"text/html")
        // ㄴ and then here i render and print the html string to my screen
        result
    }
    urlEditText.setText(INITIAL_URL) // from here is just for setting a progressbar for web pages loading
    progressView = findViewById(R.id.page_progress)
    geckoSession.progressDelegate = createProgressDelegate()
}

问题是网页没有像下面这样完全打印出来

1

我对上面的代码还有一个问题

如果我在下面编写这样的代码,我发现了这一点

    result.then { response ->
        htmlContentInStringFormat = response?.body?.bufferedReader().use { it?.readText() }
        result
    }
    geckoSession.loadData(htmlContentInStringFormat!!.toByteArray(Charsets.UTF_8),"text/html")

geckoSession.loadData() 方法比结果先执行。然后 lambda 函数

我不明白为什么会这样

所以我的问题是

  • 为什么我不能完全打印网页?
  • 为什么那个 lambda 函数执行得这么晚?
4

1 回答 1

1

您可以使用about:debuggingFirefox Desktop 连接到您的设备并在开发者控制台中检查错误。

我的猜测是该页面正在尝试从 Google 加载图像,并且不允许热链接。

如果您只想操作一些 html 请求,那么您真正应该使用的是应用程序中的内置 WebExtension,您可以在此处找到文档:https ://gv.dev/consumer/docs/web-extensions

于 2019-10-07T15:18:35.943 回答