如何在Golang中从URL中获取HTML文档的大小

huangapple go评论123阅读模式
英文:

How to retrieve html document size from url in golang

问题

我使用GoQuery来提取HTML文档中的一些值。现在我需要获取HTML文档的大小(不包括资源)。
在Firefox中,只需点击工具 -> 页面信息(常规)选项卡,就可以查看HTML文档的大小。
我也尝试过net/html包,但是我无法找到给定URL返回的HTML的大小。有什么线索吗?

英文:

I used GoQuery to retrieve some value within an HTML document. Now I need to get the size of HTML document (without assets).
In Firefox, it's as simple as Tools --> Page Info (General) tab show the Size of the HTML document.
I tried net/html package as well but I can't find the size of the returned HTML given a URL. Any clues?

答案1

得分: 3

通过以下方式获取文档:

  1. res, err := http.Get(url)
  2. if err != nil {
  3. // 处理错误
  4. }
  5. defer res.Body.Close()

现在你可以:

  1. body, err := ioutil.ReadAll(res.Body)
  2. if err != nil {
  3. // 处理错误
  4. }
  5. l := len(body)

使用GoQuery:

  1. utfBody, err := iconv.NewReader(res.Body, charset, "utf-8")
  2. if err != nil {
  3. // 处理错误
  4. }
  5. doc, err := goquery.NewDocumentFromReader(utfBody)
  6. if err != nil {
  7. // 处理错误
  8. }

关于GoQuery和读取器的更多详细信息,请参阅这里

英文:

Get the document via:

  1. res, err := http.Get(url)
  2. if err != nil {
  3. // handle error
  4. }
  5. defer res.Body.Close()

Now you can:

  1. body, err := ioutil.ReadAll(res.Body)
  2. if err != nil {
  3. // handle error
  4. }
  5. l := len(body)

To use with GoQuery:

  1. utfBody, err := iconv.NewReader(res.Body, charset, "utf-8")
  2. if err != nil {
  3. // handler error
  4. }
  5. doc, err := goquery.NewDocumentFromReader(utfBody)
  6. if err != nil {
  7. // handler error
  8. }

More datail about GoQuery and readers is here.

huangapple
  • 本文由 发表于 2015年9月8日 05:05:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/32446033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定