github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/goquery/README.md (about)

     1  # goquery - a little like that j-thing, only in Go
     2  
     3  GoQuery brings a syntax and a set of features similar to [jQuery][] to the [Go language][go]. It is based on the experimental html package and the CSS Selector library [cascadia][]. Since the experimental html parser returns tokens (nodes), and not a full-featured DOM object, jQuery's manipulation and modification functions have been left off (no point in modifying data in the parsed tree of the HTML, it has no effect).
     4  
     5  Supported functions are query-oriented features (`hasClass()`, `attr()` and the likes), as well as traversing functions that make sense given what we have to work with. This makes GoQuery a great library for scraping web pages.
     6  
     7  Syntax-wise, it is as close as possible to jQuery, with the same function names when possible, and that warm and fuzzy chainable interface. jQuery being the ultra-popular library that it is, I felt that writing a similar HTML-manipulating library was better to follow its API than to start anew (in the same spirit as Go's `fmt` package), even though some of its methods are less than intuitive (looking at you, [index()][index]...).
     8  
     9  ## Installation
    10  
    11      $ go get github.com/PuerkitoBio/goquery
    12  
    13  (optional) To run unit tests:
    14      
    15      $ cd $GOPATH/src/github.com/PuerkitoBio/goquery
    16      $ go test
    17  
    18  (optional) To run benchmarks:
    19  
    20      $ cd $GOPATH/src/github.com/PuerkitoBio/goquery
    21      $ go test -bench=".*"
    22  
    23  ## Changelog
    24  
    25  *    **v0.3.2** : Add `NewDocumentFromReader()` (thanks jweir) which allows creating a goquery document from an io.Reader.
    26  *    **v0.3.1** : Add `NewDocumentFromResponse()` (thanks assassingj) which allows creating a goquery document from an http response.
    27  *    **v0.3.0** : Add `EachWithBreak()` which allows to break out of an `Each()` loop by returning false. This function was added instead of changing the existing `Each()` to avoid breaking compatibility.
    28  *    **v0.2.1** : Make go-getable, now that [go.net/html is Go1.0-compatible][gonet] (thanks to @matrixik for pointing this out).
    29  *    **v0.2.0** : Add support for negative indices in Slice(). **BREAKING CHANGE** `Document.Root` is removed, `Document` is now a `Selection` itself (a selection of one, the root element, just like `Document.Root` was before). Add jQuery's Closest() method.
    30  *    **v0.1.1** : Add benchmarks to use as baseline for refactorings, refactor Next...() and Prev...() methods to use the new html package's linked list features (Next/PrevSibling, FirstChild). Good performance boost (40+% in some cases).
    31  *    **v0.1.0** : Initial release.
    32  
    33  ## API
    34  
    35  GoQuery exposes two classes, `Document` and `Selection`. Unlike jQuery, which is loaded as part of a DOM document, and thus acts on its containing document, GoQuery doesn't know which HTML document to act upon. So it needs to be told, and that's what the `Document` class is for. It holds the root document node as the initial Selection object to manipulate.
    36  
    37  jQuery often has many variants for the same function (no argument, a selector string argument, a jQuery object argument, a DOM element argument, ...). Instead of exposing the same features in GoQuery as a single method with variadic empty interface arguments, I use statically-typed signatures following this naming convention:
    38  
    39  *    When the jQuery equivalent can be called with no argument, it has the same name as jQuery for the no argument signature (e.g.: `Prev()`), and the version with a selector string argument is called `XxxFiltered()` (e.g.: `PrevFiltered()`)
    40  *    When the jQuery equivalent **requires** one argument, the same name as jQuery is used for the selector string version (e.g.: `Is()`)
    41  *    The signatures accepting a jQuery object as argument are defined in GoQuery as `XxxSelection()` and take a `*Selection` object as argument (e.g.: `FilterSelection()`)
    42  *    The signatures accepting a DOM element as argument in jQuery are defined in GoQuery as `XxxNodes()` and take a variadic argument of type `*html.Node` (e.g.: `FilterNodes()`)
    43  *    Finally, the signatures accepting a function as argument in jQuery are defined in GoQuery as `XxxFunction()` and take a function as argument (e.g.: `FilterFunction()`)
    44  
    45  GoQuery's complete [godoc reference documentation can be found here][doc].
    46  
    47  Please note that Cascadia's selectors do NOT necessarily match all supported selectors of jQuery (Sizzle). See the [cascadia project][cascadia] for details.
    48  
    49  ## Examples
    50  
    51  Taken from example_test.go:
    52  
    53  ```Go
    54  import (
    55    "fmt"
    56    // In real use, this import would be required (not in this example, since it
    57    // is part of the goquery package)
    58    //"github.com/PuerkitoBio/goquery"
    59    "strconv"
    60  )
    61  
    62  // This example scrapes the 10 reviews shown on the home page of MetalReview.com,
    63  // the best metal review site on the web :) (and no, I'm not affiliated to them!)
    64  func ExampleScrape_MetalReview() {
    65    // Load the HTML document (in real use, the type would be *goquery.Document)
    66    var doc *Document
    67    var e error
    68  
    69    if doc, e = NewDocument("http://metalreview.com"); e != nil {
    70      panic(e.Error())
    71    }
    72  
    73    // Find the review items (the type of the Selection would be *goquery.Selection)
    74    doc.Find(".slider-row:nth-child(1) .slider-item").Each(func(i int, s *Selection) {
    75      var band, title string
    76      var score float64
    77  
    78      // For each item found, get the band, title and score, and print it
    79      band = s.Find("strong").Text()
    80      title = s.Find("em").Text()
    81      if score, e = strconv.ParseFloat(s.Find(".score").Text(), 64); e != nil {
    82        // Not a valid float, ignore score
    83        fmt.Printf("Review %d: %s - %s.\n", i, band, title)
    84      } else {
    85        // Print all, including score
    86        fmt.Printf("Review %d: %s - %s (%2.1f).\n", i, band, title, score)
    87      }
    88    })
    89    // To see the output of the Example while running the test suite (go test), simply
    90    // remove the leading "x" before Output on the next line. This will cause the
    91    // example to fail (all the "real" tests should pass).
    92  
    93    // xOutput: voluntarily fail the Example output.
    94  }
    95  ```
    96  
    97  ## License
    98  
    99  The [BSD 3-Clause license][bsd], the same as the [Go language][golic]. Cascadia's license is [here][caslic].
   100  
   101  [jquery]: http://jquery.com/
   102  [go]: http://golang.org/
   103  [cascadia]: http://code.google.com/p/cascadia/
   104  [bsd]: http://opensource.org/licenses/BSD-3-Clause
   105  [golic]: http://golang.org/LICENSE
   106  [caslic]: http://code.google.com/p/cascadia/source/browse/LICENSE
   107  [doc]: http://godoc.org/github.com/PuerkitoBio/goquery
   108  [index]: http://api.jquery.com/index/
   109  [gonet]: http://code.google.com/p/go/source/detail?r=f7f5159120f51ba0070774d3c5907969b5fe7858&repo=net