goquery querySelector


Introduction

The Find function in goquery returns all matched elements in *Selection, but sometimes we may need only first matched element in *Selection, just like querySelector does, so I write a QuerySelector function, which accepts CSS selector as arguemnt and outputs the Selection object which contains only first matched element.

Install goquery Package

$ go get -u github.com/PuerkitoBio/goquery

Source Code

Implementation

import (
      "github.com/PuerkitoBio/goquery"
)

type object interface {
      Find(string) *goquery.Selection
}

func QuerySelector(s object, selector string) *goquery.Selection {
      return s.Find(selector).First()
}

Usage

import (
      "github.com/PuerkitoBio/goquery"
)

func main() {
      doc, err := goquery.NewDocument("https://siongui.github.io/")
      if err != nil {
              panic(err)
      }

      s := QuerySelector(doc, "meta")
      // do something with s, which contains only one matched element
}

Tested on: Ubuntu Linux 16.10, Go 1.7.5.


References:

[1]GitHub - PuerkitoBio/goquery: A little like that j-thing, only in Go. godoc
[2]Tips and tricks · PuerkitoBio/goquery Wiki · GitHub