duanben4771 2016-11-16 21:51
浏览 58

如何使用Go将网页内容转换为字符串

I am trying to use Go and the http package to get the content of a webpage into a string, then be able to process the string. I am new to Go, so I am not entirely sure where to begin. Here is the function I am trying to make.

func OnPage(link string) {

}

I am not sure how to write the function. Link is the url of the webpage to use, and result would be the string from the webpage. So for example, if I used reddit as the link, then the result would just be the string form of the content on reddit, and I could process that string in different ways. From what I have read, I want to use the http package, but as I stated before, I do not know where to begin. Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • douzhao2047 2016-11-16 22:03
    关注
    package main
    
    import (
        "fmt"
        "io/ioutil"
        "log"
        "net/http"
    )
    func OnPage(link string)(string) {
        res, err := http.Get(link)
        if err != nil {
            log.Fatal(err)
        }
        content, err := ioutil.ReadAll(res.Body)
        res.Body.Close()
        if err != nil {
            log.Fatal(err)
        }
        return string(content)
    }
    
    func main() {
        fmt.Println(OnPage("http://www.bbc.co.uk/news/uk-england-38003934"))
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题