简体   繁体   English

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

[英]How to get webpage content into a string using 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. 我正在尝试使用Go和http包将网页的内容转换为字符串,然后能够处理该字符串。 I am new to Go, so I am not entirely sure where to begin. 我是Go的新手,所以我不确定要从哪里开始。 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. 链接是要使用的网页的URL,结果将是网页中的字符串。 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. 因此,例如,如果我使用reddit作为链接,那么结果将只是reddit上内容的字符串形式,并且我可以用不同的方式处理该字符串。 From what I have read, I want to use the http package, but as I stated before, I do not know where to begin. 从阅读的内容来看,我想使用http包,但是正如我之前所说,我不知道从哪里开始。 Any help would be appreciated. 任何帮助,将不胜感激。

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"))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM