共计 1734 个字符,预计需要花费 5 分钟才能阅读完成。
goquery 的使用
因为毕设模仿知乎做了个网站,需要点数据,所以打算爬点知乎的数据,本来想通过 python 写个爬虫,但是发现 go 也有个挺好用的爬虫库——goquery,如果你学过前端,那你完全可以在半个小时之内用 goquery 写出一个爬虫
goquery 类似 jquery,它是 jquery 的 go 语言版本实现,使用它,可以很方便对 HTML 进行处理。
它可以通过 HTML Element 元素,也可以通过 Id 选择器,Class 选择器,以及属性选择器去筛选数据
github:https://github.com/PuerkitoBio/goquery
以下是我爬取知乎数据的 demo 代码
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"strconv" | |
"strings" | |
"github.com/PuerkitoBio/goquery" | |
_ "github.com/go-sql-driver/mysql" | |
) | |
func ExampleScrape() { | |
for i := 321450693; i > 321450680; i-- {res, err := http.Get("https://www.zhihu.com/question/" + strconv.Itoa(i)) | |
if err != nil || res.StatusCode != 200 {continue} | |
doc, err := goquery.NewDocumentFromReader(res.Body) | |
if err != nil {log.Fatal(err) | |
} | |
doc.Find(".QuestionHeader .QuestionHeader-content .QuestionHeader-main").Each(func(i int, s *goquery.Selection) {questionTitle := s.Find(".QuestionHeader-title").Text() | |
questionContent := s.Find(".QuestionHeader-detail").Text() | |
questionContent = questionContent[0 : len(questionContent)-12] | |
fmt.Println("questionTitle:", questionTitle) | |
fmt.Println("questionContent:", questionContent) | |
}) | |
doc.Find(".ContentItem-actions").Each(func(i int, s *goquery.Selection) {}) | |
doc.Find(".ListShortcut .List .List-item").Each(func(i int, s *goquery.Selection) {head_url, _ := s.Find("a img").Attr("src") | |
author := s.Find(".AuthorInfo-head").Text() | |
fmt.Println("head_url:", head_url) | |
fmt.Println("author:", author) | |
voters := s.Find(".Voters").Text() | |
voters = strings.Split(voters, " ")[0] | |
content := s.Find(".RichContent-inner").Text() // 带标签的可以用 Html() | |
createTime := s.Find(".ContentItem-time").Text() | |
createTime = strings.Split(createTime, " ")[1] | |
commentCount := s.Find(".ContentItem-actions span").Text() | |
fmt.Println("voters:", voters) | |
fmt.Println("content:", content) | |
fmt.Println("createTime:", createTime) | |
fmt.Println("commentCount :", commentCount) | |
}) | |
} | |
} | |
func main() {ExampleScrape() | |
} |
正文完