我现在正在自己学习 Go,并且一直在获取和解析 HTML/XML。在 Python 中,我在进行网页抓取时通常会编写以下代码:
from urllib.request import urlopen, Request
url = "http://stackoverflow.com/"
req = Request(url)
html = urlopen(req).read()
,然后我可以获得 string
或 bytes
形式的原始 HTML/XML 并继续使用它。在 Go 中,我该如何应对?我希望得到的是原始 HTML 数据,它存储在 string
或 []byte
中(尽管它可以很容易地转换,但我不介意获取哪个根本)。我考虑使用 gokogiri在 Go 中进行网络抓取的包(不确定我最终是否会使用它!),但看起来它需要原始 HTML 文本才能使用它......
那么如何获取这样的对象呢?
或者有没有更好的方法在 Go 中进行网络抓取工作?
谢谢。
最佳答案
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
res, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}
robots, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", robots)
}
会将 http://www.google.com/robots.txt
的内容返回到字符串变量 robots
中。
对于 XML 解析,请查看 the Go encoding/xml
package .
关于html - 相当于Go中Python的HTML解析函数/模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18583742/