How to get webpage content into a string using Go

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

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

huangapple
  • 本文由 发表于 2016年11月17日 05:51:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/40643030.html
匿名

发表评论

匿名网友

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

确定