英文:
How to get webpage content into a string using Go
问题
我正在尝试使用Go语言和http包将网页内容获取为字符串,然后能够处理该字符串。我对Go语言还不太熟悉,所以不太确定从哪里开始。这是我正在尝试创建的函数:
func OnPage(link string) {
}
我不确定如何编写这个函数。link
是要使用的网页的URL,result
将是网页的字符串内容。例如,如果我将reddit作为链接,那么result
将只是reddit上内容的字符串形式,我可以以不同的方式处理该字符串。根据我所了解的,我想使用http包,但正如我之前所说,我不知道从哪里开始。任何帮助将不胜感激。
英文:
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
得分: 11
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"))
}
以上是要翻译的内容。
英文:
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 := io.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"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论